【问题标题】:How to draw original function, data points and linear regression curve on the same plot with R?如何用R在同一个图上绘制原始函数、数据点和线性回归曲线?
【发布时间】:2020-11-26 19:57:21
【问题描述】:

我创建了一个带有xy 值的虚拟数据。 x 是介于 02*pi 之间的任何值。 ysin(x) +- noisenoise 是介于 00.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指定美学映射,你必须在xy(字面意思)中使用公式。

标签: r ggplot2 plot linear-regression lm


【解决方案1】:

这是一种不同的方法。 修改您的 data.frame 以增加两列:

library(dplyr)
data <- data %>%
  mutate(sin_x = sin(xs), fit = predict(fit))

现在创建您的ggplot,其中包含三个几何层,一层用于ys,一层用于sin_x,一层用于fit

data %>%
  ggplot(aes(x = xs)) +
  geom_point(aes(y = ys)) + 
  geom_line(aes(y = sin_x), color = "red", size = 0.5) + 
  geom_line(aes(y = fit), color = "black", size = 1, linetype = 2)

【讨论】:

  • 曲线不平滑。该图包含 2 条线(正弦和 lm)连接来自给定 x 值的所有输出。我需要两个功能的流畅线条
  • @krnbatta - 在这种情况下,teunbrand 的答案可能更适合您的需要
【解决方案2】:

stat_function() 层的一个鲜为人知的用例是您可以插入一个匿名函数,该函数根据您预先计算的线性模型进行预测。

ggplot(x = xs) + 
  stat_function(fun=sin, geom="line", col="green") +
  geom_point(aes(x = xs, y = ys), col="blue") +
  stat_function(fun = function(x){predict(fit, data.frame(xs = x))}, col = "red")

你的尝试非常接近,但是stat_smooth()层需要知道美学是什么,公式应该表达为美学。

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 = y ~ x + I(x^2) + I(x^3), 
              aes(x = xs, y = ys),
              col="red")

【讨论】:

  • 我无法使用您的第一个建议看到情节。
  • 我使用的是 ggplot2 3.3.2。我知道stat_function() 函数最近有更新。也许这只是一个版本问题?
猜你喜欢
  • 2019-10-22
  • 2017-08-31
  • 2021-07-18
  • 2016-07-01
  • 2021-07-05
  • 2020-07-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多