如何将计数转换为百分比

时间:2020-09-30 14:11:17

标签: r ggplot2 percentage

我正在尝试制作一个ggplot,该图显示人们参加宗教活动的频率百分比。

这是我的代码:

ggplot(D, aes(x = pew_churatd)) + geom_bar() + 
 scale_x_discrete (guide = guide_axis(angle = 90)) +
 labs(x = "How often do you attend religious services?", y = "") 

This is my graph

数据

Data

1 个答案:

答案 0 :(得分:1)

生成所需图表的一种方法是计算数据框中的百分比,并将百分比值用作ggplot()中的y轴。

textFile <- "count,answer,text
5401,1,More than once a week
11521,2,Once a week
5332,3,Once or twice a month
9338,4,A few times a year
14708,5,Seldom
17860,6,Never
707,7,Don't know
33,8,Skipped
0,9,Not asked"

df <- read.csv(text=textFile,header = TRUE)
df$response <- factor(df$answer,labels = df$text)
df$pct <- df$count / sum(df$count) * 100

library(ggplot2)

ggplot(df,aes(x=response,y=pct)) + geom_bar(stat="summary",fun=sum) + 
     scale_x_discrete (guide = guide_axis(angle = 90)) +
     labs(x = "How often do you attend religious services?", y = "Percentage")

...以及输出:

enter image description here

如果我们计算比例而不是百分比,则可以对每个注释使用scale_y_continuous()在y轴标签中生成百分号。

df <- read.csv(text=textFile,header = TRUE)
df$response <- factor(df$answer,labels = df$text)
df$proportion <- df$count / sum(df$count)

ggplot(df,aes(x=response,y=proportion)) + geom_bar(stat="summary",fun=sum) + 
     scale_x_discrete (guide = guide_axis(angle = 90)) +
     scale_y_continuous(labels = scales::percent_format()) +
     labs(x = "How often do you attend religious services?", y = "")

...以及修改后的输出:

enter image description here