You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 09:15:06