r - 如何将计数转换为百分比
问题描述
我正在尝试制作一个 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 = "")
数据
解决方案
生成所需图表的一种方法是计算数据框中的百分比,并将百分比值用作 中的 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 = "")
...以及修改后的输出:
推荐阅读
- numpy - 如何将嵌套列表转换为 numpy 数组?
- sql - 如何通过在 R 中运行 SQL 查询从数据库中选择表?
- c# - 无效的令牌/当前上下文中不存在
- php - 通过自定义批量操作处理程序更新时将订单状态更改为已确认而不发送确认电子邮件
- linux - 使用“sed 命令”在多输出文件中以“F serve..”开头的打印行
- c# - Unity 使用 OnPreRender()、OnPostRender() 仅渲染 1 个主摄像机的阴影
- javascript - 无法在日历中显示事件
- c# - 同时将元数据存储到远程服务器和本地数据库,哪个应该是第一个?
- google-analytics - 收到错误 - 缺少 google_app_id,Firebase Analytics 已禁用
- azure - 如何在 azure app 洞察中保存一些自定义 qna 制造商数据?