使用ggeffects绘制分面ggplot2时遇错误:Mapping必须由aes()创建
解决ggplot中geom_ribbon报错
mapping must be created by aes()的问题 你的报错原因很明确:调用geom_ribbon和geom_line时,错误地把数据对象pred1放在了函数的第一个参数位置。ggplot的geom类函数第一个参数是映射关系(mapping),不是数据源,必须用data=xxx的形式显式指定数据。
修正后的完整代码如下:
library(lme4) library(ggplot2) library(ggeffects) set.seed(123) df <- data.frame(xaxis = rnorm(300, 2, 3), yaxis = rnorm(300,8,3), rfactor = rep(c("A","B","C"), times = 100), species = rep(c("AA","BB"), each = 150)) fit <- lmer(yaxis ~ xaxis + species + (1|rfactor), data= df) pred1 <- ggpredict(fit, c("xaxis", "species")) pred1 <- data.frame(pred1) ggplot(df, aes(x= xaxis, y= yaxis, color = species, group = species)) + theme_classic() + geom_point() + facet_grid(.~species) + # 修正点:显式用data=pred1指定数据源 geom_ribbon(data=pred1, aes(x= xaxis, ymin= conf.low, ymax= conf.high), fill= 'grey80', inherit.aes = FALSE) + geom_line(data=pred1, aes(x= xaxis, y= predicted), inherit.aes = FALSE)
补充两个小细节:
- 因为已经通过
facet_grid(.~species)按物种分面,geom_ribbon和geom_line里的group = species可以省略,分面会自动处理分组 ggpredict返回的对象本身就可以直接给ggplot用,不用手动转成data.frame(当然转了也不影响)
内容的提问来源于stack exchange,提问作者Share
相关产品推荐
相关产品推荐

