I am making a horizontal bar plot with ggplot2
, with labels to the right of the bars. Hoe do I leave enough room for the labels so they don't fall off the chart?
This question has been asked many times before, but my question is about automatically, that means without manual adjusting, the space next to a barplot to leave enough room for labels.
The use case is a shiny app where:
- we don't know the width of the bars ahead of time
- we don't know the length of the text labels
- we don't know the text size
Example:
library(ggplot2)
data <- data.frame(
weight = c("short","longer label","medium lab"),
speed = sample(50:150,3)
)
ggplot(data, aes(x = weight, y = speed, label = weight)) +
coord_flip(clip = 'off') +
theme_minimal() +
geom_bar(stat = "identity") +
geom_text(hjust = -0.1, size = 4) +
ylim(c(0, 1.07 * max(data$speed)))
Re-run the code and you will see that the label sometimes falls off the chart on the right).
My solution so far which "kind of" works is to have some estimator for the ylim
multiplier (here, 1.07) to leave enough room. I can of course use a really high value but then we create too much whitespace.
I have also attempted to calculate the width of the grob via grid::grobWidth
, largely based on this post:
How can I access dimensions of labels plotted by `geom_text` in `ggplot2`?
However in order to calculate the actual size of a text (or other) element with this approach we need to know cex
in gpar
, but we only have a size
argument in geom_text
. I don't see how they are related (?).
I have also looked at ggprepel
and its internal code but cannot understand how to apply their methods to this particular problem.
Any help / pointers much appreciated!