如何将计数转换为百分比

问题描述

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

解决方法

生成所需图表的一种方法是计算数据框中的百分比,并将百分比值用作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,labels = df$text)
df$proportion <- df$count / sum(df$count)

ggplot(df,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

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...