As shown in the answer by @Ramnath edited by @Henrik, by passing an argument to the vjust
parameter of position_stack()
the relative position of the labels can be adjusted, and this works nicely for centered labels. In the question itself, @MYaseen208 shows how to displace the position of the labels using vertical justification. In R justification is relative to the text label's bounding box, which can result in the label's location being slightly different depending on the characters in the label (with descenders like 'g' or without like 'a'), or when the text's size or graphic device changes. Depending on the case, this may be an advantage or a disadvantage.
Here I provide, as an alternative answer that in some cases can be preferable, an example of locating the text labels nudged down from their original position by a constant distance in data units. This is equivalent to combining position_stack()
and position_nudge()
and can be achieved with position_stacknudge()
from package 'ggpp'.
Year <-
c(rep(c("2006-07", "2007-08", "2008-09", "2009-10"), each = 4))
Category <-
c(rep(c("A", "B", "C", "D"), times = 4))
Frequency <-
c(168, 259, 226, 340, 216, 431, 319, 368, 423, 645, 234, 685, 166, 467, 274, 251)
Data <- data.frame(Year, Category, Frequency)
library(ggplot2)
library(ggpp)
ggplot(Data, aes(x = Year, y = Frequency, fill = Category, label = Frequency)) +
geom_bar(stat = "identity") +
geom_text(size = 3, position = position_stacknudge(y = -60))

Created on 2022-09-03 with reprex v2.0.2