首页 > 解决方案 > 如何将计数转换为百分比

问题描述

我正在尝试制作一个 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 = "") 

这是我的图表

数据

数据

标签: rggplot2percentage

解决方案


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

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

...和输出:

在此处输入图像描述

如果我们计算比例而不是百分比,我们可以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 = "")

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

在此处输入图像描述


推荐阅读