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

ggplot中geom_smooth()拟合线与数据点不匹配问题求助

问题解决:ggplot拟合线与数据不匹配

修正后的代码

lot <- ggplot(x, aes(Emissions..kt.CO.eq..per.capita, brandstof.consumptie.in.ton)) + 
  scale_x_continuous("Emissies kt CO2-eq per capita") + 
  scale_y_continuous("energieconsumptie in transportsector per capita (ton)") + 
  geom_smooth(method = "lm") + 
  geom_text(hjust = 0, nudge_x = 0.5, size = 4, aes(label = landen))

问题原因

你在ggplot全局aes()里用x$列名的写法是错误的——这种方式会绕过ggplot的图层数据继承机制,导致geom_smooth无法正确识别全局的x/y变量映射,转而使用默认数据集(而非你的x数据集)拟合,最终出现拟合线和数据点不匹配的问题。

正确的操作是:在ggplot()中指定数据源x后,所有aes()里的变量直接写列名即可,不需要加x$前缀,这样所有图层会自动继承数据源和变量映射,保证数据一致性。

内容的提问来源于stack exchange,提问作者jiroose

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 19:52:10