首页 > 解决方案 > ggplot histogram:在每个 bin 中显示除组计数之外的总体计数

问题描述

我正在尝试使用 ggplot 生成直方图,该直方图在 x 轴上有速度,在 y 轴上有计数。此外,每个垃圾箱都显示了白天和晚上有多少垃圾箱。我需要在情节上展示自己的计数。我设法在每个条形中添加计数,但现在我想在每个条形顶部显示另一个数字,即总计数。那可能吗?

这是我的代码:

ggplot(aes(x = speedmh ) , data = GPSdataset1hDFDS48) + 
  geom_histogram(aes(fill=DayActv), bins=15, colour="grey20", lwd=0.2) + ylim(0, 400) +xlim(0,500)+
  stat_bin(bins=15, geom="text", colour="white", size=3.5,
           aes(label=..count.., group=DayActv), position=position_stack(vjust=0.5))

这是我得到的结果:

历史

如何将每个箱内的速度总数添加到每个条的顶部?理想情况下,我想制作速度比例而不是计数的直方图,但我认为目前这对我来说太复杂了。谢谢!!米娅

标签: rggplot2

解决方案


一种方法是在stat_bin不分组的情况下添加另一个命令:

library(ggplot2)
ggplot(aes(x = speedmh) , data = GPSdataset1hDFDS48) + 
  geom_histogram(aes(fill=DayActv), bins=15, colour="grey20", lwd=0.2) + ylim(0, 400) + 
  xlim(0,500) +
  stat_bin(bins=15, geom="text", colour="white", size=3.5,
           aes(label=..count.., group=DayActv), position=position_stack(vjust=0.5)) +
  stat_bin(bins=15, geom="text", colour="black", size=3.5,
           aes(label=..count..), vjust=-0.5)

在此处输入图像描述


数据:

GPSdataset1hDFDS48 <- data.frame(speedmh=rexp(1000, 0.015), DayActv=factor(sample(0:1, 1000,TRUE)))

推荐阅读