首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用回归线法和正态分布叠加法绘制and图

用回归线法和正态分布叠加法绘制and图
EN

Stack Overflow用户
提问于 2020-06-24 09:25:16
回答 1查看 646关注 0票数 3

我试图做一个图谋,以显示逻辑(或概率)回归背后的直觉。我怎样才能制作出这样的情节呢?

(Wolf & Best,“分析和因果推理的智者手册”,2015年,第155页)

实际上,我更愿意做的是,沿着y轴显示一个单一的正态分布,平均值= 0,还有一个特定的方差,这样我就可以画出从线性预测器到y轴的水平线,并且横向正态分布。就像这样:

这表明(假设我没有误解什么)

。到目前为止我还没有取得多少成功..。

代码语言:javascript
复制
library(ggplot2)

x <- seq(1, 11, 1)
y <- x*0.5

x <- x - mean(x)
y <- y - mean(y)

df <- data.frame(x, y)

# Probability density function of a normal logistic distribution 
pdfDeltaFun <- function(x) {
  prob = (exp(x)/(1 + exp(x))^2)
  return(prob)
}

# Tried switching the x and y to be able to turn the 
# distribution overlay 90 degrees with coord_flip()
ggplot(df, aes(x = y, y = x)) + 
  geom_point() + 
  geom_line() + 
  stat_function(fun = pdfDeltaFun)+ 
  coord_flip() 

EN

回答 1

Stack Overflow用户

发布于 2020-06-24 11:17:28

我认为这与你给出的第一个例子非常接近。如果这是一件您不需要重复多次的事情,那么最好在绘制之前先计算密度曲线,然后使用单独的数据来绘制这些曲线。

代码语言:javascript
复制
library(ggplot2)

x <- seq(1, 11, 1)
y <- x*0.5

x <- x - mean(x)
y <- y - mean(y)

df <- data.frame(x, y)

# For every row in `df`, compute a rotated normal density centered at `y` and shifted by `x`
curves <- lapply(seq_len(NROW(df)), function(i) {
  mu <- df$y[i]
  range <- mu + c(-3, 3)
  seq <- seq(range[1], range[2], length.out = 100)
  data.frame(
    x = -1 * dnorm(seq, mean = mu) + df$x[i],
    y = seq,
    grp = i
  )
})
# Combine above densities in one data.frame
curves <- do.call(rbind, curves)


ggplot(df, aes(x, y)) +
  geom_point() +
  geom_line() +
  # The path draws the curve
  geom_path(data = curves, aes(group = grp)) +
  # The polygon does the shading. We can use `oob_squish()` to set a range.
  geom_polygon(data = curves, aes(y = scales::oob_squish(y, c(0, Inf)),group = grp))

第二个例子非常接近您的代码。我将您的密度函数简化为标准的正常密度函数,并在stat函数中添加了一些额外参数:

代码语言:javascript
复制
library(ggplot2)

x <- seq(1, 11, 1)
y <- x*0.5

x <- x - mean(x)
y <- y - mean(y)

df <- data.frame(x, y)

ggplot(df, aes(x, y)) +
  geom_point() +
  geom_line() +
  stat_function(fun = dnorm,
                aes(x = after_stat(-y * 4 - 5), y = after_stat(x)),
                xlim = range(df$y)) +
  # We fill with a polygon, squishing the y-range
  stat_function(fun = dnorm, geom = "polygon",
                aes(x = after_stat(-y * 4 - 5), 
                    y = after_stat(scales::oob_squish(x, c(-Inf, -1)))),
                xlim = range(df$y))

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62551795

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档