ggplot柱状图分组问题:按Species拆分Treatment展示根系参数
问题需求
需要按Species(物种)分类展示三个根系参数(avg_n_roots、avg_lng_root、avg_dia_root),用颜色区分不同Treatment(处理组),将同一参数下的不同处理组柱形拆分并排显示。尝试使用dodge参数未达到预期效果,当前所有处理组被合并在同一柱中。
数据集
ths_data_1 <- tibble::tribble( ~Species, ~Treatment, ~avg_n_roots, ~avg_lng_root, ~avg_dia_root, "x1", "t1", 4, 7, 0.6, "x1", "t2", 5, 6, 0.9, "x1", "t3", 4, 8, 0.7, "x1", "t4", 3, 6, 0.8, "x2", "t1", 4, 8, 0.9, "x2", "t2", 5, 7, 0.3, "x2", "t3", 8, 8, 0.5, "x2", "t4", 3, 5, 0.7, "x3", "t1", 4, 6, 0.3, "x3", "t2", 5, 5, 0.7, "x3", "t3", 6, 4, 0.7, "x3", "t4", 9, 3, 0.8 )
尝试的R代码
ths_data_1 |> tidyr::pivot_longer(c(avg_n_roots, avg_lng_root, avg_dia_root)) |> ggplot(aes(x = Species, y = value, color = name)) + geom_col(alpha = 0, position = "dodge") + facet_wrap(~Species, scales = "free_x") + theme_minimal() + theme(legend.position = "bottom")
修正后的解决方案
代码实现
library(tidyverse) ths_data_1 |> tidyr::pivot_longer(cols = c(avg_n_roots, avg_lng_root, avg_dia_root), names_to = "Root_Parameter", values_to = "Value") |> ggplot(aes(x = Root_Parameter, y = Value, fill = Treatment)) + geom_col(position = position_dodge(width = 0.8), alpha = 0.8) + facet_wrap(~Species, scales = "free_y") + theme_minimal() + labs(x = "根系参数", y = "数值", fill = "处理组") + theme(legend.position = "bottom")
关键调整说明
- x轴与分面逻辑修正:将x轴设为根系参数(
Root_Parameter),配合facet_wrap(~Species)实现每个物种分面展示所有参数的柱形,避免原代码中每个分面仅显示单一物种的问题。 - 颜色映射修正:用
fill = Treatment将处理组映射为柱形填充色,替代原代码中用color = name标记参数名的错误逻辑。 - 并排柱形设置:
position_dodge(width = 0.8)确保同一参数下的不同处理组柱形并排显示,避免重叠合并。 - 适配数值范围:
scales = "free_y"让每个分面的y轴根据参数数值自动缩放,解决不同根系参数数值差异大的显示问题。
内容的提问来源于stack exchange,提问作者Nava Ajay Shankar A
相关产品推荐
相关产品推荐

