【问题标题】:ggplot2: How to curve small gaussian densities on a regression line?ggplot2:如何在回归线上曲线小高斯密度?
【发布时间】:2015-10-26 00:11:15
【问题描述】:

我想以图形方式显示线性(以及后来的其他类型)回归的假设。如何在回归线上添加小高斯密度(或任何类型的密度),如下图所示:

【问题讨论】:

  • 你也可以从stats.stackexchange.com得到一些帮助
  • This question 非常相关。如果您在我的回答中修改了hist 以使用dnorm 而不是数据,那么使用基图可能会让您更加接近。
  • 您是否希望它基于基础数据(即使是模拟的)?或者您是否满足于以固定间隔绘制完美的小dnorms?
  • 我正在考虑完美的小“dnorm”。在下一步中,我想对 GLM 和 GAMLSS 模型做同样的事情。

标签: r plot ggplot2 regression


【解决方案1】:

您可以计算沿拟合线的部分残差的经验密度。然后,只需使用geom_path 在每个区间中您选择的位置绘制线条即可。要添加理论分布,请沿每个部分的残差范围生成一些密度(此处使用正态密度)。对于下面的正态密度,每个部分的标准偏差是根据残差确定每个部分的,但您可以为所有部分选择一个标准偏差并使用它来代替。

## Sample data
set.seed(0)
dat <- data.frame(x=(x=runif(100, 0, 50)),
                  y=rnorm(100, 10*x, 100))

## breaks: where you want to compute densities
breaks <- seq(0, max(dat$x), len=5)
dat$section <- cut(dat$x, breaks)

## Get the residuals
dat$res <- residuals(lm(y ~ x, data=dat))

## Compute densities for each section, and flip the axes, and add means of sections
## Note: the densities need to be scaled in relation to the section size (2000 here)
dens <- do.call(rbind, lapply(split(dat, dat$section), function(x) {
    d <- density(x$res, n=50)
    res <- data.frame(x=max(x$x)- d$y*2000, y=d$x+mean(x$y))
    res <- res[order(res$y), ]
    ## Get some data for normal lines as well
    xs <- seq(min(x$res), max(x$res), len=50)
    res <- rbind(res, data.frame(y=xs + mean(x$y),
                                 x=max(x$x) - 2000*dnorm(xs, 0, sd(x$res))))
    res$type <- rep(c("empirical", "normal"), each=50)
    res
}))
dens$section <- rep(levels(dat$section), each=100)

## Plot both empirical and theoretical
ggplot(dat, aes(x, y)) +
  geom_point() +
  geom_smooth(method="lm", fill=NA, lwd=2) +
  geom_path(data=dens, aes(x, y, group=interaction(section,type), color=type), lwd=1.1) +
  theme_bw() +
  geom_vline(xintercept=breaks, lty=2)

或者,只是高斯曲线

## Just normal
ggplot(dat, aes(x, y)) +
  geom_point() +
  geom_smooth(method="lm", fill=NA, lwd=2) +
  geom_path(data=dens[dens$type=="normal",], aes(x, y, group=section), color="salmon", lwd=1.1) +
  theme_bw() +
  geom_vline(xintercept=breaks, lty=2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-10-14
    • 2014-11-14
    • 2015-12-19
    • 2017-03-30
    • 2015-06-16
    • 1970-01-01
    • 2017-11-12
    • 2013-06-26
    相关资源
    最近更新 更多