0
#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))

I am using the same ggplot for my polynomial regression but getting "Error: Aesthetics must be either length 1 or the same as the data (55): x".

Mary
  • 27
  • 5
  • Try this perhaps? https://stackoverflow.com/questions/40003508/plot-polynomial-regression-line-with-ggplot-stat-smooth and also, please make your example reproducible next time: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – william3031 Nov 25 '20 at 02:16

1 Answers1

2

You need to use x and y in the formula you pass to geom_smooth, not the variable names in your data frame.

Here's an example using some dummy data (though the structure and names are the same, so it should work on your own data):

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))


Data

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))

Created on 2020-11-24 by the reprex package (v0.3.0)

Allan Cameron
  • 147,086
  • 7
  • 49
  • 87