Reputation: 2491
I created a ggplot2 bar plot and added a label, with the bar y-value, above the bar.
d <- data.frame(
Ano=2000+5*0:10,
Populacao =c(6.1,6.5,6.9,7.3,7.7,8.0,8.3,8.6,8.9,9.1,9.3)
)
d %>% ggplot(aes(x=Ano, y=Populacao)) + geom_bar(stat="identity") +
geom_text(aes(label=Populacao), vjust=-0.5)
Notice how the label on the highest column gets cut.
Is there a way for the plot to automatically adjust to the presence of the label?
EDIT: I know I can adjust this manually with scale_y_continuous(breaks=seq(0, 10, 1), limits=c(0,10))
Upvotes: 8
Views: 2577
Reputation: 78
This will not adjust the size of the plot (e.g. it will not help if for instance you set the vjust
argument in geom_text()
to -2), but it will at least prevent the portion of the label outside the y-axis upper bound from being clipped:
d %>% ggplot(aes(x=Ano, y=Populacao)) + geom_bar(stat="identity") +
geom_text(aes(label=Populacao), vjust=-0.5) +
coord_cartesian(clip = "off")
In any case, like tonitonov, I would also suggest expanding the axes by further adding something like + scale_y_continuous(expand = expansion(mult = c(0,0.1)))
at the end of your ggplot
pipe. This will set the upper y-axis bound 10% above your highest data point, while also removing the extra space at the bottom, which I particularly do not like, but you can tweak these to meet your needs; the default behavior for scale_y_continuous()
is to scale 5% both at the top/bottom).
Upvotes: 1