如何在同一图表中按fire_severity等级绘制两组箱线图?
问题描述
我已经绘制出一张箱线图,该图展示了包含所有火灾等级的地表覆盖比例分布。
使用的数据是一张包含fire_severity(火灾等级)、ecozone(生态区)、cover_type(覆盖类型)、proportion(覆盖比例)字段的表格。
现在需要过滤数据,仅保留fire_severity为Low和High的条目,按fire_severity等级分别绘制以ecozone为X轴、proportion为Y轴的箱线图,最终效果是分为Low和High两个子图,每个子图中按生态区分组展示覆盖比例的箱线分布。
我编写了如下代码但无法正常运行:
table_long4 %>% filter(fire_severity == "Low", fire_severity == "High") %>% ggplot(table_long4, aes(x = cover_type, y = proportion, fill = ecozone)) + geom_boxplot(outlier.shape = NA, outlier.size = 0.5) + scale_fill_manual(values = c("red", "green", "blue"), name = "") + labs(y = "Proportion of ground cover", x = "Cover Type") + theme_bw() + theme(axis.title.x = element_blank(), legend.position = "top", legend.direction = "horizontal", legend.title = element_blank(), legend.justification = "left", legend.key.size = unit(0.6, "cm")) + scale_color_manual(values = c("red", "green", "blue"), name = "") + facet_wrap(~ Low + High)
代码问题修正
你的代码存在几个关键问题,逐一修正:
- 过滤条件错误:
filter(fire_severity == "Low", fire_severity == "High")用了逻辑与,一条数据不可能同时属于Low和High,应该用%in%匹配多个值:filter(fire_severity %in% c("Low", "High")) - ggplot数据传递错误:管道符
%>%已经把过滤后的数据传给ggplot,不需要再手动指定原数据集table_long4,直接映射美学属性即可。 - X轴映射错误:目标图的X轴是
ecozone,你代码里写的是cover_type,需要修正为ecozone。 - 分面语法错误:
facet_wrap(~ Low + High)是错误用法,应该按fire_severity字段分面,正确写法是facet_wrap(~ fire_severity)。 - 多余的颜色映射:你的箱线图用的是
fill(填充色)映射,没有用到color(边框色),可以删除scale_color_manual这一行,避免冗余。
修正后的完整代码
table_long4 %>% filter(fire_severity %in% c("Low", "High")) %>% ggplot(aes(x = ecozone, y = proportion, fill = ecozone)) + geom_boxplot(outlier.shape = NA, outlier.size = 0.5) + scale_fill_manual(values = c("red", "green", "blue"), name = "") + labs(y = "地表覆盖比例", x = "生态区") + theme_bw() + theme(axis.title.x = element_blank(), legend.position = "top", legend.direction = "horizontal", legend.title = element_blank(), legend.justification = "left", legend.key.size = unit(0.6, "cm")) + facet_wrap(~ fire_severity)
内容的提问来源于stack exchange,提问作者Kaitlin Green
相关产品推荐
相关产品推荐

