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

绘制含city与sqft交互项的线性模型时出现‘找不到city对象’错误求助

解决ggplot2绘制交互项线性模型时"Can't find object 'city'"报错

问题根源

你用geom_smooth时,formula里的x、y是aes映射变量的别名,但city不在这个别名体系里,直接写y ~ x * city会导致ggplot找不到这个变量——毕竟当前aes里只映射了sqft和price。

两种可行修复方案

方案1:把city加入aes分组/颜色映射

让ggplot明确识别city作为分组变量,这样交互项就能正常调用:

ggplot(data, aes(x = sqft, y = price, group = city)) +
  geom_point() +
  geom_smooth(method = "lm", formula = y ~ x * city, se = FALSE) +
  labs(x = "sqft", y = "price", 
       title = "Linear model with interaction term by city")

要是想给不同城市的线条加颜色区分,把group = city换成color = city就行,还能自动生成图例。

方案2:在geom_smooth里用原始列名并指定数据

直接放弃x/y别名,用数据里的真实列名,同时明确传递数据集:

ggplot(data, aes(x = sqft, y = price)) +
  geom_point() +
  geom_smooth(method = "lm", formula = price ~ sqft * city, data = data, se = FALSE) +
  labs(x = "sqft", y = "price", 
       title = "Linear model with interaction term by city")

为啥之前散点图能跑?

因为散点图只用到了aes里已经映射好的sqft和price,根本没调用city变量,自然不会报错。

内容的提问来源于stack exchange,提问作者Atli Harðarson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 18:30:10