如何在ggplot2棒棒糖图中为每个x值生成4个独立茎
解决ggplot2棒棒糖图茎与点不对应的问题
问题核心:你的代码中geom_segment未将type作为分组依据,导致position_dodge无法对每个trait下不同type的茎进行水平偏移,所有茎都重叠在trait的中心位置,和偏移后的点无法一一对应。
解决方法:在geom_segment的aes映射中添加group = type,让position_dodge基于type分组来调整茎的位置,实现每个点对应独立的竖茎。
修改后的完整代码:
set.seed(123) # 保证结果可复现 df_long <- data.frame( trait = rep(c("Trait1", "Trait2", "Trait3", "Trait4", "Trait5"), each = 4), type = rep(c("eur_ita", "eur_ita_2", "eur_ita_3", "eur_ita_4"), times = 5), value = c(runif(5, 5, 15), runif(5, 8, 20), runif(5, 1, 12), runif(5, 4, 18)), macro_cat3 = rep(c("Category1", "Category2"), each = 10) # 分为两个大类别 ) ggplot(df_long, aes(x = trait, y = value, color = type, shape = type, alpha = type)) + # 添加棒棒糖茎(关键修改:新增group = type) geom_segment( aes(x = trait, xend = trait, y = 0, yend = value, group = type), position = position_dodge(width = 0.8), # 水平偏移茎 linewidth = 0.6 # 调整茎的粗细 ) + # 添加棒棒糖头部 geom_point( position = position_dodge(width = 0.8), # 水平偏移点 size = 3 # 调整点的大小 ) + facet_wrap(~ macro_cat3, scales = "free_x", ncol = 4) + labs(x = "Trait", y = "Percentage of r2", color = "Type", shape = "Type", alpha = "PRS Type") + scale_color_manual( values = c( "eur_ita" = "red", "eur_ita_2" = "black", "eur_ita_3" = "green", "eur_ita_4" = "gray" ) ) + scale_alpha_manual( values = c( "eur_ita" = 1, "eur_ita_2" = 0.9, "eur_ita_3" = 0.9, "eur_ita_4" = 1 ), guide = "none" ) + scale_shape_manual( values = c( "eur_ita" = 18, "eur_ita_2" = 18, "eur_ita_3" = 19, "eur_ita_4" = 19 ) ) + theme_minimal() + theme( axis.text.x = element_text(angle = 45, hjust = 1, size = 10), strip.text = element_text(size = 12), legend.position = "bottom", panel.border = element_rect(color = "black", fill = NA, linewidth = 0.8), strip.background = element_blank() )
关键说明:
- 添加
group = type后,geom_segment会根据type对每个trait下的茎进行分组,配合position_dodge(width = 0.8),茎的偏移位置会和geom_point的偏移位置完全对应,实现每个点对应独立的竖茎。 - 确保
geom_segment和geom_point的position_dodge(width = 0.8)参数一致,保证两者偏移量匹配。
内容的提问来源于stack exchange,提问作者Khaleesi95
相关产品推荐
相关产品推荐

