R ggplot2:在条形图的顶部绘制百分比值,并在geom_bar函数中计算比例 [英] R ggplot2: Plot percentage values on top of Bar chart with proportion calculated within the geom_bar function

查看:1051
本文介绍了R ggplot2:在条形图的顶部绘制百分比值,并在geom_bar函数中计算比例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用的数据:

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

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

Below is the code I have used to plot the bar chart :

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函数本身中采用了比例.我想知道如何在栏的顶部显示相应的百分比值.条形图看起来像

I have taken the proportions in the geom_bar function itself. I wanted to know how can I display the respective percentage values on top of the bar. The bar chart looks like

我确实在堆栈溢出时进行搜索,但是大多数都已计算出百分比.我想知道是否可以绘制百分比值.

I did search on stack overflow but most of them had percentages already calculated. I wanted to know if in my way if I can plot the percentage values.

我尝试过

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

得到下面的图,但是有一种方法可以调整文本:

Got the below graph , but is there a way to adjust the text:

推荐答案

使用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)

这篇关于R ggplot2:在条形图的顶部绘制百分比值,并在geom_bar函数中计算比例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆