【发布时间】:2020-11-26 19:57:21
【问题描述】:
我创建了一个带有x 和y 值的虚拟数据。 x 是介于 0 和 2*pi 之间的任何值。 y 是 sin(x) +- noise。 noise 是介于 0 和 0.5 之间的随机值。
我使用以下公式创建了一条线性回归曲线:fit <- lm(ys ~ xs + I(xs^2) + I(xs^3))。
我可以使用以下代码仅绘制原始正弦函数和点:
plot(sin, 0, 2*pi,col="green",xlim = c(-0.5, 6.5), ylim = c(-1.5, 1.5))
points(xs, ys,col="blue")
我还想将拟合曲线添加到同一个图中。我做了一些研究并想出了以下代码:
library(ggplot2)
ggplot(x = xs) +
stat_function(fun=sin, geom="line", col="green") +
geom_point(aes(x = xs, y = ys), col="blue") +
stat_smooth(method = "lm", formula = ys ~ xs + I(xs^2) + I(xs^3), col="red")
但它只是在绘制点。如何用R在同一张图上绘制原始函数、数据点和线性回归曲线?
这是整个代码:
xs <- c(0, 2*pi)
ys <- c(runif(1,0,0.5), -runif(1,0,0.5))
for(i in 1:20){
x <- runif(1, 0, 2*pi)
y <- sin(x)
noise <- runif(1,0,0.5)
if(i%%2 == 0){
y <- y + noise
}
else{
y <- y - noise
}
xs <- c(xs, x)
ys <- c(ys, y)
}
data <- data.frame(xs, ys)
fit <- lm(ys ~ xs + I(xs^2) + I(xs^3))
#plot(sin, 0, 2*pi,col="green",xlim = c(-0.5, 6.5), ylim = c(-1.5, 1.5))
#points(xs, ys,col="blue")
#abline(fit)
library(ggplot2)
ggplot(x = xs) +
stat_function(fun=sin, geom="line", col="green") +
geom_point(aes(x = xs, y = ys), col="blue") +
stat_smooth(method = "lm", formula = ys ~ xs + I(xs^2) + I(xs^3), col="red")
【问题讨论】:
-
ggplot(data, aes(x = xs, y = ys)) + stat_function(fun=sin, geom="line", col="green") + geom_point(col="blue") + stat_smooth(method = "lm", formula = y ~ poly(x, degree = 3), col="red") -
你必须将一个data.frame传递给ggplot2,你必须为每个stat/geom或
ggplot指定美学映射,你必须在x和y(字面意思)中使用公式。
标签: r ggplot2 plot linear-regression lm