如何在R Studio中用ggplot2的geom_bar()绘制学生经济资助占比柱状图
完整实现:用ggplot2绘制经济资助学生占比柱状图
嘿,我来帮你搞定这个ggplot2的柱状图需求!你想要展示获得与未获得经济资助的学生占比,基于你现有的comparison_table数据框,我准备了两种实用的实现方案,你可以根据需求选择:
第一步:先构建可复现的数据框
首先,把你给出的数据整理成可直接运行的R代码,方便后续测试和绘图:
# 构建你的数据框(和你提供的内容完全一致) comparison_table <- data.frame( Students1 = c("PELL", "NOPELL", "LOAN", "NOLOAN"), Percentage1 = c(0.4059046, 0.5018954, 0.4053371, 0.2290538), financial_assistance1 = c(TRUE, FALSE, TRUE, FALSE), stringsAsFactors = FALSE )
方案一:展示每个细分资助类型的占比
如果你想保留PELL、NOPELL、LOAN、NOLOAN这些细分类型,同时区分是否获得资助,可以用并列柱状图展示:
library(ggplot2) # 绘制细分类型的分组柱状图 ggplot(comparison_table, aes(x = Students1, y = Percentage1, fill = financial_assistance1)) + geom_bar(stat = "identity", position = "dodge") + # 并列展示不同分组 scale_fill_manual(values = c("#E69F00", "#56B4E9"), labels = c("未获得资助", "获得资助")) + # 自定义颜色和标签 labs( title = "不同经济资助类型的学生占比", x = "学生类型", y = "占比", fill = "资助状态" ) + theme_minimal() + scale_y_continuous(labels = scales::percent_format()) # 将小数转为百分比显示
方案二:汇总展示“获得/未获得资助”的总占比
如果你的核心需求是直观对比获得资助和未获得资助两类的总占比,我们可以先对数据进行汇总,再绘图:
# 需要用到dplyr进行数据汇总,如果没安装先运行:install.packages("dplyr") library(dplyr) library(ggplot2) # 按资助状态分组,汇总总占比 summary_table <- comparison_table %>% group_by(financial_assistance1) %>% summarise(Total_Percentage = sum(Percentage1)) %>% ungroup() # 绘制汇总后的柱状图,添加百分比标签 ggplot(summary_table, aes(x = financial_assistance1, y = Total_Percentage, fill = financial_assistance1)) + geom_bar(stat = "identity") + scale_fill_manual(values = c("#E69F00", "#56B4E9"), labels = c("未获得资助", "获得资助")) + labs( title = "获得与未获得经济资助的学生总占比", x = "资助状态", y = "总占比", fill = "资助状态" ) + theme_minimal() + scale_y_continuous(labels = scales::percent_format()) + geom_text(aes(label = scales::percent(Total_Percentage)), vjust = -0.5, size = 4) # 在柱子上方添加百分比标签,更直观
关键代码说明
stat = "identity":因为我们已经有了计算好的占比数值,所以不需要ggplot自动统计频数,直接使用现有数据绘制柱子。scale_y_continuous(labels = scales::percent_format()):把小数形式的占比转为百分比显示,大幅提升可读性。- 汇总数据时用
dplyr的group_by()和summarise(),能快速合并同一资助状态下的占比总和。
内容的提问来源于stack exchange,提问作者Reeza
相关产品推荐
相关产品推荐

