绘制R和ggplot2中正态分布的垂直密度 [英] Plot vertical density of normal distribution in R and ggplot2

查看:87
本文介绍了绘制R和ggplot2中正态分布的垂直密度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to plot vertical normal distributions in ggplot2 into an existing linear regression model, in order to visualize homoscedasticity.
I currently have the following code and plot:

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") 

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

And I would like to insert density curves like this (just facing the other way round):

推荐答案

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)

这篇关于绘制R和ggplot2中正态分布的垂直密度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆