r - 多项式回归的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”。
解决方案
您需要在传递给的公式中使用x
和,而不是数据框中的变量名称。y
geom_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 日创建
推荐阅读
- php - 您的要求无法解决为一组可安装的软件包。- Laravel 流明邮件
- linux - linux - df 命令说磁盘 100% 已使用,但实际上并非如此
- asp.net-mvc-4 - 需要一种在网页中嵌入 rdlc 设计器的方法
- java - 单击毕加索时如何显示图像
- crystal-reports - 如何将一些十进制数字删除到业务伙伴帐龄(摘要报告)字段?
- php - 如何使用确切数量的参数查找函数调用
- c++ - 什么会在这个程序中产生内存泄漏
- xamarin.forms - 将 AutoMapper 从 7.0.0 升级到 9.0.0 后面临映射异常
- api - Microsoft Graph 活动 - 401 AAD 身份验证失败
- kotlin - 如何抑制 Detekt 的 WildcardImport 和 MatchingDeclarationName?