首页 > 解决方案 > 多项式回归的ggplot2有问题

问题描述

#linear regression 
fit1 <- lm(temp ~ usage ,data= electemp) 

#polynomial regression 
fit2 <- lm(temp ~ poly(electemp$usage,degree), data = electemp)

ggplot(data=electemp, aes(x=temp,y=usage))+geom_point()+
stat_smooth(method="lm",col="red"). #linear regression 

ggplot(electemp, aes(usage, temp) ) +
  geom_point() +
  stat_smooth(method = lm, formula=temp~ poly(electemp$usage, 3, raw=TRUE))

我在多项式回归中使用相同的 ggplot,但得到“错误:美学必须是长度 1 或与数据 (55) 相同:x”。

标签: rggplot2

解决方案


您需要在传递给的公式中使用x和,而不是数据框中的变量名称。ygeom_smooth

这是一个使用一些虚拟数据的示例(尽管结构和名称是相同的,所以它应该适用于您自己的数据):

library(ggplot2)

fit1 <- lm(temp ~ usage ,data= electemp) 

fit2 <- lm(temp ~ poly(usage, 3), data = electemp)

ggplot(electemp, aes(usage, temp)) +
  geom_point() +
  stat_smooth(method = "lm", col = "red") 

ggplot(electemp, aes(usage, temp) ) +
  geom_point() +
  stat_smooth(method = lm, formula= y ~ poly(x, 3))


数据

set.seed(1)
electemp <- data.frame(usage = 1:60,
                       temp = 20 + .2 * 1:60 - 0.02*(1:60)^2 +
                              0.0005 * (1:60)^3 + rnorm(60, 0, 5))

reprex 包(v0.3.0)于 2020 年 11 月 24 日创建


推荐阅读