如何用ggplot实现堆叠与并列混合的柱状图(非数值X轴)
解决方案
要实现「Bidrag与Depot堆叠、同时和GaranteretYdelse并列」的效果,需要先调整数据结构新增分组变量,再通过ggplot的分组与位置参数实现组合布局:
步骤1:调整数据结构
在长格式数据中新增DodgeGroup变量,将Bidrag和Depot归为同一堆叠组,GaranteretYdelse设为独立组:
produkt_A_data_long <- produkt_A_data %>% tidyr::pivot_longer(cols = -Grundlag, names_to = "Attribute", values_to = "Value") %>% # 定义分组规则:Bidrag和Depot属于堆叠组,其余为独立组 mutate(DodgeGroup = case_when( Attribute %in% c("Bidrag", "Depot") ~ "Stacked", TRUE ~ "Standalone" ))
步骤2:绘制组合柱状图
通过group参数指定分组逻辑,使用position_dodge2()实现「组内堆叠、组间并列」的效果,preserve = "single"确保不同组的柱子宽度一致:
ggplot(produkt_A_data_long, aes(x = Grundlag, y = Value, fill = Attribute, group = interaction(DodgeGroup, Attribute))) + geom_bar(stat = "identity", position = position_dodge2(width = 0.9, preserve = "single")) + labs(title = "Aggregated Values by Grundlag", x = "Grundlag", y = "Value", fill = "Attribute") + theme_minimal()
可选调整
若要改变堆叠顺序,可通过factor()指定Attribute的层级,层级靠前的元素会被堆叠在下方:
# 示例:让Depot在下方,Bidrag在上方 produkt_A_data_long$Attribute <- factor(produkt_A_data_long$Attribute, levels = c("Depot", "Bidrag", "GaranteretYdelse"))
内容的提问来源于stack exchange,提问作者Victoria Kledal
相关产品推荐
相关产品推荐

