如何在R ggplot的geom_label框中居中文本?

时间:2017-09-05 21:14:29

标签: r ggplot2

在R中使用geom_label作为我的(gg)图时,我注意到文本上面的空间比下面的空间要大。如何将文本对齐到标签框的中间?

x <- data.frame(x = c("Being not", "Creative"), y = c(0.5, 1), text = c(543,12345))

g <- ggplot(data=x, aes(x, y)) + geom_bar(stat = 'identity', fill=c("red4","cornflowerblue"))

g + geom_label(aes(y = -Inf, label = text), vjust = -2)

# increasing `label.padding` here to exaggerate the white space
g + geom_label(aes(y = -Inf, label = text), vjust = -2, label.padding = unit(1, "lines")

Illustrative Sample

1 个答案:

答案 0 :(得分:2)

指定显式y坐标以放置标签而不是vnudge。

g + geom_label(aes(y = .25, label = text), label.padding = unit(1, "lines"))

enter image description here

更好的是,将y坐标向量传递给y aes,指定中点。

g + geom_label(aes(y = c(.25, .5) label = text), label.padding = unit(1, "lines"))

enter image description here