ggplot geom_histogram + geom_errorbar

Hello the community, I'm struggling with something I would wish was simple (but I might be just too novice to find out how to get what I want). I'm making use of geom_histogram with custom binwidth parameter. So fare, so good. But I'd wish to draw Poisson error bars which is computer by using the square root of the bin content: bincontent +/- sqrt(bincontent). And I'm not successful at it. How would you proceed without having to compute or extract yourself the bin contents ?

Here is some histogram without the desired error bars:

library(ggplot2)
dt <- data.frame(n  = c(18, 19, 10, 24, 11, 15, 16, 15, 15, 14))

ggplot(dt, aes(x = n)) +
  geom_histogram(binwidth = 5)

And here is an attempt which didn't work:

library(ggplot2)

dt <- data.frame(n  = c(18, 19, 10, 24, 11, 15, 16, 15, 15, 14))

ggplot(dt, aes(x = n)) +
  geom_histogram(binwidth = 5) +
  geom_errorbar(aes(y = ..count.., ymin = ..count.. + sqrt(..count..), ymax = ..count.. - sqrt(..count..)), stat = 'count')

Thank you for your help

with stat = "count" you don't extract the x-axis position of the bins, stat = "bin" should do the job:

ggplot(dt, aes(x = n)) +
  geom_histogram(binwidth = 5) +
  geom_errorbar(aes(ymin = ..count.. - sqrt(..count..) , 
                    ymax = ..count.. + sqrt(..count..) ), 
                stat = 'bin', binwidth = 5)

unfortunately it seems you cannot decrease the width of the error-bars using this setting...

This topic was automatically closed 42 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.