Xiang Li
Xiang Li

Reputation: 23

plot fitted line in r

fit_bmi <- glm(df$genhlth_NC ~ poly(df$bmi_NC, 2, raw = TRUE))
plot(df$bmi_NC, df$genhlth_NC, col=rgb(red=0.2, green=0.2, blue=1.0, alpha=0.01))
lines(df$bmi_NC, predict(fit_bmi), col = 'red')

I wanted to generate a fitted line on my plot. However, I got a weird plot with the code above. Could someone help me with this?

Pic of Weird Plot

Upvotes: 1

Views: 120

Answers (1)

IRTFM
IRTFM

Reputation: 263301

Copied comment: You need to sort both x and y by the x-values. You should also learn to use formulas without the data.frame names in the body of the formula and use the data parameter for the dataframe name. The donvoter was probably reacting to the lack of a data example, but the source of the error was quite clear from the plotted pic.

I tested my advice in the text formerly known as "comment" with this code and it seems to deliver the expected result:

fit_bmi <- glm(genhlth ~ poly(bmi, 2, raw = TRUE), data=dat)
plot(genhlth ~ bmi, data=dat)
lines(dat$bmi[order(dat$bmi)], predict(fit_bmi)[order(dat$bmi)],lwd=3, col = 'red')

Here's a dat-object constructed with a structure I assume is similar to your data object:

dat <- data.frame(genhlth = sample(1:5, size=100, repl=TRUE,
                                   prob=c(.1, .2, .3, .2, .2) ),
                   bmi = rnorm(100,30,5) )
table(dat$genhlth)
#------------
 1  2  3  4  5 
 6 24 25 30 15 

enter image description here

Upvotes: 1

Related Questions