Here's a test df:
a <- 5:8
b <- c("A", "B", "C", "D")
df <- data.frame(a,b)
I'd like to create a bar plot and add text above each bar, a certain distance beneath the top, thus I use y=Inf, vjust=2
, however the letters are now aligned by their tops and not the bottom of the letter (i.e. they don't sit on the same horizontal line). Is there a way to change that (without having to fiddle around with the values to something like vjust=2.45
or so for the "shorter" ones)?
ggplot(df, aes(x=b, y=a)) + geom_bar(stat="identity") +
scale_y_continuous(limits = c(0,9)) +
annotate('text', x=1, y=Inf, vjust=2, label = "a", parse=TRUE) +
annotate('text', x=2, y=Inf, vjust=2, label = "a", parse=TRUE) +
annotate('text', x=3, y=Inf, vjust=2, label = "b", parse=TRUE) +
annotate('text', x=4, y=Inf, vjust=2, label = "b", parse=TRUE)
hjust = 0 does what you want. hjust stands for horizontal justification, 0 will be left-justified, 0.5 will be centered, and 1 will be right-justified.
Left alignment can be requested by setting sep = "\\l" , right alignment by "\\r" and center alignment by "\\c" . Mind the backslashes, as if they are omitted, strings would be aligned to the character l, r or c respectively. Default value is "\\r" , thus right alignment.
Text geoms are useful for labeling plots. They can be used by themselves as scatterplots or in combination with other geoms, for example, for labeling points or for annotating the height of bars. geom_text() adds only text to the plot. geom_label() draws a rectangle behind the text, making it easier to read.
The answer is quite simple: Use a single "annotate" command instead of multiple ones.
Edit: If the parse
argument is set to TRUE
(as in your snippet), this method fails.
:) Good luck.
library(ggplot2)
a <- 5:8
b <- c("A", "B", "C", "D")
df <- data.frame(a,b)
ggplot(df, aes(x=b, y=a)) + geom_bar(stat="identity") +
scale_y_continuous(limits = c(0,10)) +
# This is the difference to yor code:
annotate("text", x = 1:4, y = Inf, vjust=2, label = c("a", "a", "b", "b"))
This is actually included in the R documentation of annotate
: (last line of ?annotate
)
p + annotate("text", x = 2:3, y = 20:21, label = c("my label", "label 2"))
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