在ggplot多系列条形图中按条件为不合格条形添加阴影
没问题,这事儿好办!咱们可以通过给数据加个标记列,再结合ggplot的图层叠加来实现你要的阴影标记效果,下面是具体的步骤和代码,直接就能用:
实现步骤
1. 预处理数据,添加标记列
首先咱们先把示例数据加载进来,然后新增一个flag列,专门用来标记哪些条形需要加阴影——也就是满足CV>20或者Sample_size<30的行:
library(tidyverse) # 你的示例数据 df <- structure(list(Group = c("A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J"), Perc = c(38, 38, 46, 27, 18, 39, 43, 27, 38, 40, 39, 39, 50, 32, 33, 41, 52, 32, 43, 43), Lower_CI = c(36, 36, 36, 15, 8, 31, 30, 14, 18, 23, 38, 37, 40, 21, 15, 31, 40, 17, 24, 27), Upper_CI = c(39, 40, 57, 39, 27, 47, 55, 40, 58, 56, 41, 41, 60, 44, 51, 51, 64, 47, 63, 60), CV = c(2, 2, 11, 12, 28, 11, 15, 6, 18, 13, 2, 2, 10, 19, 5, 13, 12, 23, 14, 20), Sample_size = c(30, 15, 140, 40, 69, 75, 56, 256, 45, 536, 4852, 785, 36, 48, 315, 120, 83, 15, 123, 45), Period = c(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2)), row.names = c(NA, -20L), class = c("tbl_df", "tbl", "data.frame")) # 添加标记列:符合条件的标记为TRUE df <- df %>% mutate(flag = CV > 20 | Sample_size < 30)
2. 绘制带阴影标记的条形图
这里提供两种实现方式,你可以根据自己的需求选:
方式一:灰色半透明背景阴影
用geom_rect给需要标记的条形添加灰色背景,放在条形图层的下方,效果自然:
ggplot(df, aes(x = Group, y = Perc, fill = factor(Period))) + # 先画阴影背景:只给flag为TRUE的条形添加 geom_rect( data = df %>% filter(flag), aes(xmin = as.numeric(Group) - 0.3, xmax = as.numeric(Group) + 0.3, ymin = 0, ymax = max(df$Upper_CI) * 1.05), # ymax设为比最大置信上限稍高一点,避免截断 fill = "gray80", alpha = 0.3 ) + # 绘制分组条形 geom_col(position = position_dodge(width = 0.6), width = 0.5) + # 添加置信区间误差线 geom_errorbar(aes(ymin = Lower_CI, ymax = Upper_CI), position = position_dodge(width = 0.6), width = 0.2) + # 调整标签和主题 labs(title = "不同Period下各组百分比差异", x = "组别", y = "百分比", fill = "时期") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5))
方式二:斜线填充阴影(更贴近Excel示例)
如果想要和Excel示例一样的斜线阴影,可以用ggpattern包来实现,先安装这个包,然后用带图案的条形:
# 先安装包(第一次用需要安装) # install.packages("ggpattern") library(ggpattern) ggplot(df, aes(x = Group, y = Perc, fill = factor(Period))) + # 带图案的条形:只有flag为TRUE的才显示斜线 geom_col_pattern( aes(pattern = flag), position = position_dodge(width = 0.6), width = 0.5, pattern_fill = "gray50", pattern_density = 0.05, pattern_spacing = 0.02 ) + # 添加误差线 geom_errorbar(aes(ymin = Lower_CI, ymax = Upper_CI), position = position_dodge(width = 0.6), width = 0.2) + # 调整标签和主题 labs(title = "不同Period下各组百分比差异", x = "组别", y = "百分比", fill = "时期", pattern = "标记项") + theme_minimal() + theme(plot.title = element_text(hjust = 0.5)) + # 手动设置图案:未标记的无图案,标记的用斜线 scale_pattern_manual(values = c(FALSE = "none", TRUE = "stripe"))
内容的提问来源于stack exchange,提问作者barnesybee
相关产品推荐
相关产品推荐

