I'm trying to add an annotation (a label) to a ggplot2 plot (using R) with a position relative to another element, namely, above a bar in a bar chart.
I'm trying do this as part of a package, and (so) the following example is a bit contrived, but I hope it demonstrates the challenge.
Here is what I tried first, in which I position the label at the y variable value plus (so the label is above the bar) an additional 5% of the y variable's value.
library(ggplot2)
d <- data.frame(x = c("var1", "var2"), y = c(.2, 4))
ggplot(d, aes(x = x, y = y)) +
geom_col() +
annotate("text", x = d$x, y = d$y + (.05 * d$y), label = "hi!")

Close, but not quite there. If I make this much larger than 5%, then the label on the bar for the larger y value becomes too far from the bar, whereas if I make this much smaller than 5%, then the label becomes too close to (and overlapping with) the bar.
I tried to take the square root of the y value:
ggplot(d, aes(x = x, y = y)) +
geom_col() +
annotate("text", x = d$x, y = d$y + sqrt(.05 * d$y), label = "hi!")

This more or less works except in extreme cases for which this fails (the labels become very far or near the top of the bar) and so I am wondering whether there is a more general way to add a label (or another ggplot2 annotation) relative to the position of another element in a more dynamic way.
You can try using vjust with geom_text():
ggplot(d, aes(x = x, y = y)) +
geom_col() + geom_text(aes( label = "hi!"), vjust = -0.5)
Should work pretty well even in extreme cases:
d <- data.frame(x = c("var1", "var2"), y = c(.2, 100))

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With