gpt4 book ai didi

r - 在 R 和 ggplot2 中绘制正态分布的垂直密度

转载 作者:行者123 更新时间:2023-12-03 21:14:44 24 4
gpt4 key购买 nike

我想将 ggplot2 中的垂直正态分布绘制到现有的线性回归模型中,以便可视化同方差性。
我目前有以下代码和情节:

x <- runif(100, 0, 15)
y <- 1000 + 200*x + rnorm(100, 0, 300)
df <- data.frame(x, y)

lm_fit <- lm(y ~ x, data = df)


#with regression line
ggplot(df, mapping = aes(x=x, y=y)) + geom_point(color="blue") + geom_smooth(method='lm', se=FALSE, color="red")

sample regression

我想插入这样的密度曲线(正好相反):
sample wanted result

最佳答案

library(ggplot2)

x <- runif(100, 0, 15)
y <- 1000 + 200*x + rnorm(100, 0, 300)
df <- data.frame(x, y)
lm_fit <- lm(y ~ x, data = df)

k <- 2.5
sigma <- sigma(lm_fit)
ab <- coef(lm_fit); a <- ab[1]; b <- ab[2]

x <- seq(-k*sigma, k*sigma, length.out = 50)
y <- dnorm(x, 0, sigma)/dnorm(0, 0, sigma) * 3

x0 <- 0
y0 <- a+b*x0
path1 <- data.frame(x = y + x0, y = x + y0)
segment1 <- data.frame(x = x0, y = y0 - k*sigma, xend = x0, yend = y0 + k*sigma)
x0 <- 5
y0 <- a+b*x0
path2 <- data.frame(x = y + x0, y = x + y0)
segment2 <- data.frame(x = x0, y = y0 - k*sigma, xend = x0, yend = y0 + k*sigma)
x0 <- 10
y0 <- a+b*x0
path3 <- data.frame(x = y + x0, y = x + y0)
segment3 <- data.frame(x = x0, y = y0 - k*sigma, xend = x0, yend = y0 + k*sigma)

ggplot(df, mapping = aes(x=x, y=y)) + geom_point(color="blue") +
geom_smooth(method='lm', se=FALSE, color="red") +
geom_path(aes(x,y), data = path1, color = "green") +
geom_segment(aes(x=x,y=y,xend=xend,yend=yend), data = segment1) +
geom_path(aes(x,y), data = path2, color = "green") +
geom_segment(aes(x=x,y=y,xend=xend,yend=yend), data = segment2) +
geom_path(aes(x,y), data = path3, color = "green") +
geom_segment(aes(x=x,y=y,xend=xend,yend=yend), data = segment3)

enter image description here

关于r - 在 R 和 ggplot2 中绘制正态分布的垂直密度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61589781/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com