r - 可能的 ggplot2 错误 : inconsistent normalizations of overlaid histograms

标签 r ggplot2 histogram

我最近无意中发现了 ggplot2 中的一些奇怪行为。以下代码

N <- 1000
coin <- rep(c(0,1),N/2)
N1 <- sum(coin)
N0 <- sum(1-coin)
values <- rep(0,N)
values[coin==0] <- rnorm(N0,mean=0,sd=1)
values[coin==1] <- rnorm(N1,mean=0,sd=1)
dat = data.frame('Value'=values,'Category'=as.factor(coin))

创建一个包含一个数字列和一个因子列的数据集,属于两个类别的事件数量相等:

> summary(dat)
     Value           Category
 Min.   :-3.901785   0:500   
 1st Qu.:-0.669807   1:500   
 Median : 0.020031           
 Mean   :-0.008229           
 3rd Qu.: 0.650803           
 Max.   : 3.195819   

但是,当绘制按类别分割的值列时,类别 1 的规范化程度比类别 0 高得多:

ggplot(dat,aes(x=Value,fill=Category)) + geom_histogram(alpha=0.5) + theme_bw()

enter image description here

这看起来很奇怪。两个直方图的 bin 宽度看起来是相等的,它们应该是相等的,但事件的总计数并不相等,它们应该是相等的。类别0直方图实际上是整个数据集的直方图:

ggplot(dat,aes(x=Value)) + geom_histogram(alpha=0.5) + theme_bw()

enter image description here

这是 ggplot2 错误,还是我犯了一些我没有注意到的错误? (顺便说一下,如果我用“A”和“B”替换类别 0 和 1,我会得到同样的结果)。

系统详情:

  • Mac OS X High Sierra
  • R 版本 3.4.0 (2017-04-21)
  • ggplot2_2.2.1

最佳答案

geom_histogram 默认通过参数 position="stack" 将条形堆叠在一起。这对于同时查看整体构成和每个部分的贡献很有用,但对于直接比较各部分就没那么有用了。您可以通过将位置参数更改为 "identity" 来覆盖它,例如:

ggplot(dat,aes(x=Value,fill=Category)) +
 geom_histogram(alpha=0.5, position="identity") + theme_bw()

Histogram using position="identity"

关于r - 可能的 ggplot2 错误 : inconsistent normalizations of overlaid histograms,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50817980/

相关文章:

正则表达式匹配所有不是4位数字的数字

r - 将基本图形和 ggplot 图形合并到图形设备的子图形中

r - 使用 qplot 的多层平滑图

R Shiny ggplot 对 varSelectInput 有反应

R 历史 : relationship between 'breaks' value and number/size of bins

python :使用 numpy.histogram

r - 在 Fedora Linux 中最近更新的 R 中安装 Quantstrat

r - 更改 ggplot 凹凸图上的文本大小

r - 几何直方图 : What is the default origin of the first bin?

r - 中断/退出脚本