在ggplot2中对齐文本注释

时间:2014-09-22 11:57:32

标签: r ggplot2

这是一个测试df:

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

我想创建一个条形图并在每个条形图上方添加文本,在顶部下方一定距离,因此我使用y=Inf, vjust=2,但字母现在由顶部而不是底部对齐信(即他们不坐在同一条水平线上)。有没有办法改变它(不必为{“1}}或类似的东西摆弄”更短的“?

vjust=2.45

enter image description here

1 个答案:

答案 0 :(得分:5)

答案很简单:使用单个“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

这实际上包含在annotate的R文档中:( ?annotate的最后一行)

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