【问题标题】:having problem with ggplot2 for polynomial regression多项式回归的ggplot2有问题
【发布时间】:2020-11-24 21:37:10
【问题描述】:
#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”。

【问题讨论】:

标签: r ggplot2


【解决方案1】:

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

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

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 package (v0.3.0) 于 2020 年 11 月 24 日创建

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 2011-04-23
    • 2019-01-24
    相关资源
    最近更新 更多