R ggplot2:绘制条形图顶部的百分比值,其中比例在geom_bar函数中计算

时间:2017-09-17 09:34:43

标签: r ggplot2 geom-bar geom-text

使用的数据:

structure(list(Year = c(2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 2014L, 
2014L, 2014L, 2014L, 2014L, 2014L), Rating = c(4L, 4L, 4L, 3L, 
4L, 4L, 4L, 3L, 4L, 3L, 4L, 4L, 4L, 4L, 4L, 4L, 5L, 5L, 5L, 5L, 
5L, 5L, 5L, 5L, 5L, 5L, 5L, 4L, 5L, 5L, 5L, 5L, 4L, 4L, 4L, 5L, 
5L, 4L, 5L, 5L, 5L, 5L, 4L, 4L, 4L, 5L, 5L)), .Names = c("Year", 
"Rating"), class = "data.frame", row.names = c(NA, -47L))

以下是我用来绘制条形图的代码:

ggplot(subset(ws_inf, ws_inf$Year=="2014"), mapping = aes(x=Rating)) +
  geom_bar(mapping = aes(y = ..prop.., group = 1)) + 
  ggtitle("2014") +
  ylab("Percentage") + 
  xlab("Rating")

我已经采用了geom_bar函数本身的比例。我想知道如何在条形图上显示相应的百分比值。条形图看起来像

enter image description here

我确实搜索了堆栈溢出,但大多数已经计算了百分比。我想知道我是否可以绘制百分比值。

我试过这个

ggplot(subset(ws_inf, ws_inf$Year=="2014"), mapping = aes(x=Rating)) +
  geom_bar(mapping = aes(y = (..prop..)*100, group = 1)) +
  geom_text(stat='count', aes(label=round((..prop..)*100,2)), vjust=-0.5) + 
  ggtitle("2014") +
  ylab("Percentage") + 
  xlab("Rating")

得到以下图表,但有没有办法调整文字:

enter image description here

1 个答案:

答案 0 :(得分:1)

使用vjust。怎么样:

 library(ggplot2)
   ggplot(subset(ws_inf,ws_inf$Year=="2014"), mapping = aes(x=Rating)) +
     geom_bar(aes(y = ..prop.., group = 1)) +
     geom_text(aes( y = ..prop.., label = scales::percent(..prop..)), stat = "count", vjust = -1)

enter image description here