label gets cut on ggplot2 bar plot
Asked Answered
K

1

7

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) 

enter image description here

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))

Kill answered 18/7, 2016 at 12:40 Comment(1)
Semi-automatic solution would be to use something like expand_limits(y = max(d$Populacao * 1.05)).Naturalism
L
1

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).

Lotti answered 24/6 at 22:27 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.