如何让geom_bar()实现分组避让并设置为灰度/黑白配色?
解决ggplot分组条形图与灰度配色问题
问题根源
你当前的代码用了两个独立的geom_bar分别绘制Pre和Post数据,这种方式没法让ggplot识别出需要分组避让的关联关系,所以position="dodge"只对第二个条形生效,无法实现正确的分组效果。同时未指定灰度配色的刻度设置,默认使用了彩色填充。
解决步骤
1. 整理数据为长格式
ggplot更适配长格式数据(每行对应一个观测),我们需要把Pre和Post的数据集合并成包含分组信息的统一数据框:
# 先安装并加载所需包(未安装时运行:install.packages(c("dplyr", "tidyr"))) library(dplyr) library(tidyr) # 合并Pre和Post数据为长格式 combined_data <- tibble( Pre = Pre$preQ17, Post = Post$postQ7 ) %>% pivot_longer( cols = everything(), # 选中所有列 names_to = "Survey", # 新增列存储分组标识(Pre/Post) values_to = "prevalence" # 新增列存储患病率数值 )
2. 绘制分组条形图并设置灰度配色
用整理好的长数据绘图,只需一个geom_bar就能实现分组避让,同时通过scale_fill_grey设置灰度配色:
p <- ggplot(combined_data, aes(x = factor(prevalence), fill = Survey)) + # 设置分组避让,width参数控制条形间的间距 geom_bar(position = position_dodge(width = 0.8), alpha = 0.8) + labs( title = "Impressions of Prevalence of All Rare Diseases Combined", x = "Prevalence", y = "Number of students", fill = "Survey" ) + scale_x_discrete( labels = c("1 in 2", "1 in 5", "1 in 10", "1 in 100", "1 in 1,000", "1 in 10,000", "1 in 100,000") ) + # 灰度配色,start为深色值,end为浅色值,可自行调整0-1之间的数值 scale_fill_grey(start = 0.3, end = 0.7) + theme( panel.background = element_rect(fill = 'white', colour = 'white'), plot.title = element_text(hjust = 0.5) ) # 显示图形 p # 保留你的t检验代码 res <- t.test(Pre$preQ17, Post$postQ7) res
可选:手动指定黑白/灰度颜色
如果需要纯黑+浅灰的固定配色,替换上述代码中的scale_fill_grey为:
scale_fill_manual(values = c("Pre" = "black", "Post" = "grey70"))
效果说明
- 分组避让:通过
position_dodge让同一x轴类别下的Pre和Post条形并排显示 - 灰度配色:
scale_fill_grey自动生成渐变灰度,scale_fill_manual可自定义具体灰度值
内容的提问来源于stack exchange,提问作者Anony Mouse
相关产品推荐
相关产品推荐

