ggplot2绘制折线图添加误差栏时报错:找不到'mntd.obs.z'
问题:ggplot2绘制带误差栏折线图时提示找不到
mntd.obs.z对象 尝试用ggplot2绘制带误差栏的折线图,运行代码时报错,提示第4层(geom_errorbar)计算美学属性时找不到对象mntd.obs.z。mean_data数据集包含所需的mean_mntd.obs.z和sd_mntd.obs.z变量,移除geom_errorbar图层后代码可正常运行。
原代码
mntd_loco<-ggplot(SES_MNTD_loco, aes(x = camp, y = mntd.obs.z, color = season, group = season)) + geom_point(alpha = 0.3, size= 3.5) + # 添加带透明度的散点 geom_line(data = mean_data, aes(y = mean_mntd.obs.z), linewidth= 1.5) + # 添加均值折线 geom_point(data = mean_data, aes(y = mean_mntd.obs.z), size = 5) + # 添加均值点 geom_errorbar(data = mean_data, aes(ymin = mean_mntd.obs.z-sd_mntd.obs.z, ymax= mean_mntd.obs.z + sd_mntd.obs.z ), linewidth= 1.5)+ geom_hline(yintercept = 0, linetype = "longdash", color = "black", linewidth= 2) + labs(x = "海拔", y = "SES MNTD", color = "季节") + # 设置坐标轴和图例标签 scale_color_manual(values=c('#999999','#E69F00')) + theme_classic()
报错信息
Error in `geom_errorbar()`: ! Problem while computing aesthetics. ℹ Error occurred in the 4th layer. Caused by error in `FUN()`: ! object 'mntd.obs.z' not found
mean_data数据集
> mean_data # A tibble: 8 × 4 # Groups: camp [4] camp season mean_mntd.obs.z sd_mntd.obs.z <fct> <chr> <dbl> <dbl> 1 DG dry -0.413 0.607 2 DG wet -0.230 0.346 3 PC dry -1.08 0.302 4 PC wet -0.974 0.417 5 CL dry -1.08 0.173 6 CL wet -1.07 0.235 7 MS dry -0.299 0.690 8 MS wet -0.382 0.61
生成mean_data的代码
mean_data <- SES_MNTD_loco %>% group_by(camp, season) %>% summarize(mean_mntd.obs.z = mean(mntd.obs.z), sd_mntd.obs.z = sd(mntd.obs.z))
SES_MNTD_loco数据集前6行
> head(SES_MNTD_loco) ntaxa mntd.obs mntd.rand.mean mntd.rand.sd mntd.obs.rank mntd.obs.z mntd.obs.p camp season DG_dry.1 36 17.59933 20.40015 6.001859 355 -0.4666597 0.35464535 DG dry DG_dry.2 35 21.60363 20.52625 6.591346 643 0.1634539 0.64235764 DG dry DG_dry.3 43 13.62599 19.26860 5.472003 103 -1.0311768 0.10289710 DG dry DG_dry.4 35 23.39255 20.61614 7.202468 754 0.3854798 0.75324675 DG dry DG_dry.5 42 12.40775 19.34753 6.245307 64 -1.1111996 0.06393606 DG dry DG_dry.6 40 17.04743 19.79749 6.598712 389 -0.4167577 0.38861139 DG dry
解决方案
报错核心原因是:ggplot2会继承全局设置的美学映射(aes(y = mntd.obs.z)),但mean_data中不存在mntd.obs.z变量,geom_errorbar继承该映射后,会尝试在mean_data里查找这个变量,从而触发报错。
有两种可行的解决方法:
方法一:显式指定
geom_errorbar的y映射
在geom_errorbar的aes中补充y = mean_mntd.obs.z,覆盖全局的y映射,其他美学属性(x、color、group)可正常继承:geom_errorbar(data = mean_data, aes(y = mean_mntd.obs.z, ymin = mean_mntd.obs.z-sd_mntd.obs.z, ymax= mean_mntd.obs.z + sd_mntd.obs.z ), linewidth= 1.5)方法二:关闭美学映射继承
在geom_errorbar中添加inherit.aes = FALSE,同时手动指定所需的所有映射(x、color、group):geom_errorbar(data = mean_data, aes(x = camp, ymin = mean_mntd.obs.z-sd_mntd.obs.z, ymax= mean_mntd.obs.z + sd_mntd.obs.z, color = season, group = season), linewidth= 1.5, inherit.aes = FALSE)
推荐使用方法一,代码更简洁,仅需补充必要的y映射即可解决问题。
内容的提问来源于stack exchange,提问作者Guillermo Uceda
相关产品推荐
相关产品推荐

