简体   繁体   中英

lines() function in base R plot giving several lines instead of smooth line

I am attempting to add a smoother to a plot of a regression model I have. I was just using base R to plot my X and Y vectors and add a smoother using plot() and then lines(). I've done this before, and it worked, but today I am given a plot with multiple lines connecting the points as opposed to one smooth line through all the data. I can't figure out what is different about this piece of code I have written, so I am hoping someone here could help me identify the issue.

Here is my code. I am using data I randomly generated to practice something else:

X and random variable vectors to create 'Y':

X <- rnorm(100, mean = 10, sd = 1)
epsilon <- rnorm(100, 0, 1)

Y:

b0 <- 0.27
b1 <- 0.49
b2 <- 0.62
b3 <- 0.8

Y <- b0 + b1*X + b2*2^2 + b3*X^3 + epsilon

Creating df and reg model/Yhat:

df = data.frame(Y,X,epsilon)
reg <- lm(Y ~ I(X^3), data = df)
Yhat <- fitted.values(reg)
cbind(df, Yhat) -> df

plot:

plot(X, Y)
lines(X, Yhat, col = "blue", lwd = 0.5)

For this to work, the X values have to be sorted and the Y values sorted according to their corresponding X values:

X <- rnorm(100, mean = 10, sd = 1)
epsilon <- rnorm(100, 0, 1)

b0 <- 0.27
b1 <- 0.49
b2 <- 0.62
b3 <- 0.8

Y <- b0 + b1*X + b2*2^2 + b3*X^3 + epsilon

df = data.frame(Y,X,epsilon)
reg <- lm(Y ~ I(X^3), data = df)
Yhat <- fitted.values(reg)
cbind(df, Yhat) -> df

plot(X, Y)
lines(X[order(X)], Yhat[order(X)], col = "blue", lwd = 0.5)

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM