Reputation: 10123
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)
Upvotes: 5
Views: 2242
Reputation: 953
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"))
Upvotes: 5