Search code examples
rggplot2bar-charthistogram

How to align the bars of a histogram with the x axis?


Consider this simple example

library(ggplot2)
dat <- data.frame(number = c(5, 10, 11 ,12,12,12,13,15,15))
ggplot(dat, aes(x = number)) + geom_histogram()

enter image description here

See how the bars are weirdly aligned with the x axis? Why is the first bar on the left of 5.0 while the bar at 10.0 is centered? How can I get control over that? For instance, it would make more sense (to me) to have the bar starting on the right of the label.


Solution

  • This will center the bar on the value

    data <- data.frame(number = c(5, 10, 11 ,12,12,12,13,15,15))
    ggplot(data,aes(x = number)) + geom_histogram(binwidth = 0.5)
    

    Here is a trick with the tick label to get the bar align on the left.. But if you add other data, you need to shift them also

    ggplot(data,aes(x = number)) + 
      geom_histogram(binwidth = 0.5) + 
      scale_x_continuous(
        breaks=seq(0.75,15.75,1), #show x-ticks align on the bar (0.25 before the value, half of the binwidth) 
        labels = 1:16 #change tick label to get the bar x-value
        )
    

    other option: binwidth = 1, breaks=seq(0.5,15.5,1) (might make more sense for integer)