2

curve fitting

Hello, I want to know why the fitted curve in the picture looks so bad and is not just one smooth line?

plot(df$Q,df$C)
cur=lm(C~I(1/Q),data=df)
lines(df$Q, predict(cur), col = "green")

What am I missing?

Micho
  • 3,929
  • 13
  • 37
  • 40
user195366
  • 465
  • 2
  • 13
  • 2
    Because the values were not ordered by the x-axis values. – IRTFM Jun 26 '18 at 00:07
  • To start, read here on how to make a sample data set: https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example – Adam Smith Jun 26 '18 at 00:08

1 Answers1

0

Instead you should sort both the predicted and X values by the X values order. One way to do that is to pass an ordered set of values to the lm function. Then the predicted values will also reflect that ordering:

 plot( df$Q, dg$C )
 cur  <- lm(C~I(1/Q), data=df[order[df$Q), ] )
 lines(df$Q, predict(cur), col = "green")
IRTFM
  • 258,963
  • 21
  • 364
  • 487