【问题标题】:Logistic regression + histogram with ggplot2使用ggplot2进行逻辑回归+直方图
【发布时间】:2015-11-04 12:09:50
【问题描述】:

我有一些二进制数据,我想在同一个图中同时绘制逻辑回归线 0 和 1 的相对频率的直方图。

我在这里使用包 popbio 遇到了一个非常好的实现:shizuka lab's page

这是一个与 library(popbio) 一起运行的 MWE(由 shizuka lab 提供)

bodysize=rnorm(20,30,2) # generates 20 values, with mean of 30 & s.d.=2
bodysize=sort(bodysize) # sorts these values in ascending order.
survive=c(0,0,0,0,0,1,0,1,0,0,1,1,0,1,1,1,0,1,1,1) # assign 'survival' to these 20 individuals non-randomly... most mortality occurs at smaller body size
dat=as.data.frame(cbind(bodysize,survive))

#and now the plot
library(popbio)
logi.hist.plot(bodysize,survive,boxp=FALSE,type="hist",col="gray")

产生

现在,可以用 ggplot2 做到这一点吗?

【问题讨论】:

  • ggplot 和双 y 轴是“哲学上的困难”,但类似的东西可能是可能的。
  • @Heroka 我同意这种理念——我通常尽量不使用它们。不过,我可以看到,在这种情况下,它很有意义——您可以真正了解数据,而使用 geom_smooth()+geom_point() 您只能看到一个点而不是点的质量,所以您对数据没有清晰的概念。我试过 geom_smooth()+geom_point(position='jitter') 但在我的情况下,我有很多数据,而且抖动到处都是。

标签: r ggplot2 histogram logistic-regression


【解决方案1】:

这里有一些想法

ggplot(dat, aes(x = bodysize, y = survive)) + 
  geom_dotplot(
    aes(fill = factor(survive)), method = "histodot", binpositions = "all", 
    stackgroups = TRUE, stackdir = "centerwhole", binwidth = 1
  ) +
  geom_smooth(method = "glm", family = "binomial")

ggplot(dat, aes(x = bodysize, y = survive)) + 
  geom_hex(bins = 10) +
  geom_smooth(method = "glm", family = "binomial")

ggplot(dat, aes(x = bodysize, y = survive)) + 
  geom_bin2d(bins = 10) +
  geom_smooth(method = "glm", family = "binomial")

【讨论】:

  • +1 有很多可能性,但仍然没有到达那里。我的意思是,它们都很好,但它们不像 popbio 示例那样可读。
  • 更复杂的解决方案是计算直方图。然后计算直方图条的坐标。然后在geom_rect() 中使用这些坐标。
  • geom_smooth() 现在将family 作为method.args 列表:geom_smooth(method = "glm", method.args = list(family = "binomial"))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-12-19
  • 2015-02-21
  • 2018-08-11
  • 1970-01-01
  • 2020-09-27
  • 2017-09-25
  • 2016-06-17
相关资源
最近更新 更多