Align text annotation in ggplot2

Here's the df test:

a <- 5:8
b <- c("A", "B", "C", "D")
df <- data.frame(a,b)

I would like to create a bar chart and add text above each bar, a certain distance below the top, so I use y=Inf, vjust=2, however, the letters are now aligned at their vertices, and not to the bottom of the letter (i.e. they do not sit on the same horizontal line) . Is there a way to change this (without having to bother with values ​​somehow vjust=2.45or the like for "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)

enter image description here

+4
source share
1 answer

: "annotate" . : parse TRUE ( ), . :) .

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"))

enter image description here

R- annotate: ( ?annotate)

p + annotate("text", x = 2:3, y = 20:21, label = c("my label", "label 2"))
+5

All Articles