[英]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().
我只是使用基数 R 来绘制我的 X 和 Y 向量,然后使用 plot() 和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 和随机变量向量来创建“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 和 reg 模型/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
值进行排序,并根据对应的X
值对Y
值进行排序:
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.