When adding text labels next to (or above) bars with geom_text
, there is no way to automatically leave enough room for the label. Example:
library(ggplot2)
pdata <- data.frame(group = c("A","B"),
value = c(10,20),
label = c("First label", "A long label"))
ggplot(pdata, aes(x = group, y = value)) +
coord_flip() +
geom_bar(stat = "identity") +
geom_text(aes(label = label), hjust = -0.1)
I can of course manually change the axis limit so that the label fits, but I would like this to always work regardless of the input data.
My idea was to calculate the width of the labels in the current device (in relative 0-1 units of the figure region, or in user coordinates, both would work), but strwidth
is not sufficient, and the grid
package has some interesting functions which I cannot get to do what I want (convertWidth
in particular).
How do I calculate the width of the label
in the current plot so that I can adjust the axis limit automatically?
Thanks!