使用GGPLOT对比两组内多变量均值并绘制分组柱状图
解决方案
我们可以用dplyr处理数据计算均值,ggplot2绘制柱状图,再用patchwork(或gridExtra)将两个图横向拼接,实现需求效果。
步骤1:加载所需包
library(dplyr) library(ggplot2) library(patchwork) # 用于拼接图形
步骤2:计算各组各Score变量的均值
先对数据分组,计算每个Score变量的均值,并将宽格式数据转为长格式,方便绘图:
mean_scores <- DB %>% group_by(Group) %>% summarise(across(starts_with("Score"), mean)) %>% pivot_longer(cols = starts_with("Score"), names_to = "Score", values_to = "Mean")
步骤3:绘制两个柱状图并拼接
分别绘制两组的均值柱状图,再横向排列:
# Group 2的均值柱状图 p_group2 <- ggplot(filter(mean_scores, Group == "2"), aes(x = Score, y = Mean)) + geom_col(fill = "#3498db") + labs(title = "Group 2 mean scores", x = "Score变量", y = "均值") + theme_minimal() # Group 1的均值柱状图 p_group1 <- ggplot(filter(mean_scores, Group == "1"), aes(x = Score, y = Mean)) + geom_col(fill = "#2ecc71") + labs(title = "Group 1 mean scores", x = "Score变量", y = "均值") + theme_minimal() # 横向拼接两个图 p_group2 + p_group1
替代方案(无patchwork时)
如果未安装patchwork,可以用gridExtra包的grid.arrange实现拼接:
library(gridExtra) grid.arrange(p_group2, p_group1, ncol = 2)
内容的提问来源于stack exchange,提问作者Sari Katish
相关产品推荐
相关产品推荐

