r - ggplot2 因子直方图显示概率质量而不是计数

标签 r ggplot2

我正在尝试使用优秀的 ggplot2,使用 bar geom 来绘制概率质量而不是计数。但是,使用 aes(y=..密度..) 分布的总和不等于 1(但很接近)。我认为问题可能是由于因子的默认 binwidth 造成的。这是问题的示例,

age <- c(rep(0,4), rep(1,4))
mppf <- c(1,1,1,0,1,1,0,0)
data.test <- as.data.frame(cbind(age,mppf))
data.test$age <- as.factor(data.test$age)
data.test$mppf <- as.factor(data.test$mppf)
p.test.density <- ggplot(data.test, aes(mppf, group=age, fill=age)) +
geom_bar(aes(y=..density..), position='dodge') +
scale_y_continuous(limits=c(0,1))
dev.new()
print(p.test.density)

我可以通过保持 x 变量连续并设置 binwidth=1 来解决这个问题,但这看起来不太优雅。

data.test$mppf.numeric <- as.numeric(data.test$mppf)
p.test.density.numeric <- ggplot(data.test, aes(mppf.numeric, group=age, fill=age)) + 
geom_histogram(aes(y=..density..), position='dodge', binwidth=1)+ 
scale_y_continuous(limits=c(0,1))
dev.new()
print(p.test.density.numeric)

最佳答案

我认为您几乎已经弄清楚了,并且一旦您意识到您需要一个条形图而不是直方图,您就会明白了。

包含分类数据的条形图的默认宽度为 0.9(请参阅 ?stat_bingeom_bar 的帮助页面不会提供默认的条形图宽度,但会向您发送到stat_bin以供进一步阅读。)。鉴于此,您的图显示了条形宽度为 0.9 的正确密度。只需将宽度更改为 1,您就会看到您期望看到的密度值。

ggplot(data.test, aes(x = mppf, group = age, fill = age)) +
  geom_bar(aes(y=..density..), position = "dodge", width = 1) +
  scale_y_continuous(limits=c(0,1))

关于r - ggplot2 因子直方图显示概率质量而不是计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18634484/

相关文章:

r - 当 "Sign in with Google temporarily disabled for this app"时你如何进行?

r - 如何防止x轴与facet_wrap(~variable)重叠ggplotly

r - 在 ggpairs 中加入独立的图例(采取 2)

r - 使用Knitr和RStudio将ggplot2输出嵌入LaTeX pdf中

r - 如何将误差线组织到ggplot中堆积条形图中的相关条形图?

r - 在同一面板中为每个组绘制单独的线性和二次回归图

r - 将数字转换为日期

r - R:获取属性值作为向量

r - 当范围变化时,按月从 df 中提取开始和结束日期

使用多个 aes 设置绘制构面时从 ggplot 中的图例中删除元素