求助:用R语言ggplot绘制基于species的seed type分面箱线图
问题描述
我正在用R语言编写代码,想基于species条件绘制箱线图。
数据详情
| species | seed type | germination time |
|---|---|---|
| A | initial | 10.5 |
| A | initial | 11.3 |
| B | stored | 12.5 |
数据说明:包含34个物种(species),2种种子类型(stored和initial),germination time为数值型变量。我需要绘制目标样式的图形,且必须用ggplot实现。尝试了以下分面绘制代码,但未得到预期效果:
plot2 <- ggplot(mydata, aes(x=factor(species), y=mgt,fill = species))+ geom_boxplot(outliers = F)+ theme(legend.position = "bottom") plot3 <- plot2 + coord_flip()+ facet_wrap(seed_type) + scale_x_discrete(name = "Seed Type") + scale_y_continuous(name = "Germination Time") plot3
修正方案及代码
核心问题梳理
- 隐藏异常值的参数错误:
geom_boxplot中正确隐藏异常值的参数是outlier.shape = NA,而非outliers = F - 坐标轴标签匹配错误:x轴实际对应
species,不能命名为"Seed Type" - 变量名需统一:需确认代码中
mgt是否对应数据里的germination time,建议先规范列名避免空格问题
修正后的分面绘制代码
# 先规范列名(避免空格导致的报错) mydata <- mydata %>% rename(germination_time = `germination time`, seed_type = `seed type`) # 绘制分面箱线图 ggplot(mydata, aes(x = species, y = germination_time, fill = species)) + geom_boxplot(outlier.shape = NA) + # 隐藏异常值 coord_flip() + # 翻转坐标轴 facet_wrap(~seed_type, ncol = 1) + # 按种子类型分面,单列布局 labs(x = "物种", y = "发芽时间") + # 修正坐标轴标签 theme(legend.position = "bottom")
备选:同一物种的两种种子类型箱线图并排展示
如果目标图是让同一物种的两种种子类型箱线图并排(而非分面),可使用以下代码:
ggplot(mydata, aes(x = species, y = germination_time, fill = seed_type)) + geom_boxplot(outlier.shape = NA, position = position_dodge(width = 0.8)) + # 并排展示 coord_flip() + labs(x = "物种", y = "发芽时间", fill = "种子类型") + theme(legend.position = "bottom")
内容的提问来源于stack exchange,提问作者Bandara Rathnathilaka
相关产品推荐
相关产品推荐

