如何在ggplot2单个柱状图中同时使用stack和dodge并保留填充色
解决方案
要实现同周的不同年份堆叠柱并列展示、同时保留风险分类填充色的效果,有两种常用实现方案:
方案1:使用ggh4x扩展包(代码更简洁,效果可控)
ggh4x包提供了原生ggplot没有的position_dodge_stack()位置调整函数,可直接同时实现堆叠+并列逻辑:
# 首次使用需先安装 # install.packages("ggh4x") library(ggplot2) library(dplyr) library(ggh4x) # 沿用你之前构造的数据集 Weeks_Years <- c(rep("42 - 2021" , 5) , rep("42 - 2020" , 5) , rep("43 - 2021" , 5) , rep("43 - 2020" , 5)) Risk_Category <- rep(c("A","B","C","D","E") , 4) Exp_premium <- abs(rnorm(20 , 0 , 20)) newdata <- data.frame(Weeks_Years,Risk_Category,Exp_premium) newdata$year = as.factor(ifelse(newdata$Weeks_Years == "42 - 2020", 2020, ifelse(newdata$Weeks_Years == "43 - 2020", 2020, 2021))) # 提取周号做x轴 newdata <- newdata %>% mutate(week = substr(Weeks_Years, 1, 2)) # 绘图 newdata %>% ggplot(aes( x = week, y = Exp_premium, fill = Risk_Category, group = year )) + geom_col( position = position_dodge_stack(width = 0.8), aes(alpha = year) ) + scale_alpha_manual(values = c("2020" = 1, "2021" = 0.4), guide = "none") + labs(x = "周 / 年份", y = "预期保费")
方案2:原生ggplot实现(无需额外安装包)
通过构造组合x轴分组、调整刻度展示的方式模拟并列效果:
# 数据预处理:构造组合分组列 newdata <- newdata %>% mutate( week = substr(Weeks_Years, 1, 2), x_group = interaction(week, year, sep = "_") ) # 绘图 newdata %>% ggplot(aes(x = x_group, y = Exp_premium, fill = Risk_Category)) + geom_col(position = "stack", aes(alpha = year)) + scale_alpha_manual(values = c(1, 0.4), guide = "none") + # 调整x轴标签,仅显示周号,模拟同周两年份柱子并列的视觉效果 scale_x_discrete( labels = c("42_2020" = "42", "42_2021" = "", "43_2020" = "43", "43_2021" = "") ) + labs(x = "周 / 年份", y = "预期保费")
原代码问题原因
你之前拆分了2020、2021两个图层分别设置position_dodge,此时每个图层内的风险分类也会被当做并列分组排列,自然无法形成堆叠效果。
内容的提问来源于stack exchange,提问作者Aswiderski
相关产品推荐
相关产品推荐

