Reputation: 15
I am trying to generate a histogram using ggplot which on the x axis has speeds and on the y axis has the counts. In addition, each bin shows how many of those were during the day and night. I need to present the counts themselves on the plot. I managed to add the counts within each bar but now I would like to present another number, the total count, on top of each bar. Is that possible?
This is my code:
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))
and this is the result I get:
How do I add the total count of speeds within each bin to the top of every bar? Ideally I would like to make this histogram of proportions of speeds instead of counts, but I think that is too complicated for me at the moment. Thank you!! Mia
Upvotes: 0
Views: 1333
Reputation: 19541
One way is to add another stat_bin
command without the grouping:
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)
Data:
GPSdataset1hDFDS48 <- data.frame(speedmh=rexp(1000, 0.015), DayActv=factor(sample(0:1, 1000,TRUE)))
Upvotes: 2