在ggplot中移动文本

时间:2015-12-09 09:52:46

标签: r ggplot2

使用此代码可以打印下面的图表。如您所见,百分比打印在条形边框上。我想把它们放在酒吧上面。有没有办法实现这个目标?

p <- ggplot(data=iris, aes(x=factor(Species), fill=factor(Species)))
p + geom_bar() + scale_fill_discrete(name="Species")  + labs(x="") +geom_text(aes(y = (..count..),label = scales::percent((..count..)/sum(..count..))), stat="bin",colour="darkgreen") + theme(legend.position="none")

enter image description here

1 个答案:

答案 0 :(得分:3)

只需向y添加任意值。

p <- ggplot(data=iris, aes(x=factor(Species), fill=factor(Species)))
p + geom_bar() + scale_fill_discrete(name="Species")  + labs(x="") +geom_text(aes(y = (..count..) + 10,label = scales::percent((..count..)/sum(..count..))), stat="bin",colour="darkgreen") + theme(legend.position="none")

enter image description here

或者,根据Heroka的评论,使用vjust,这是一个更好的解决方案

p <- ggplot(data=iris, aes(x=factor(Species), fill=factor(Species)))
p + geom_bar() + scale_fill_discrete(name="Species")  + labs(x="") + 
  geom_text(aes(y = (..count..), 
                label = scales::percent((..count..)/sum(..count..))), 
            stat="bin", 
            colour="darkgreen", vjust = -0.5) + 
  theme(legend.position="none")

enter image description here

但是由于这会使得顶部的事情变得非常狭窄,您可能需要添加+ expand_limits(y = c(0, 60))以便为标签提供更多空间。