Raffael Raffael - 3 months ago 40
R Question

Align bars of histogram centered on labels

For layouting reasons I would like to position the histgram bars centered on the labels, such that the middle of a bar is on top of the label.

library(ggplot2)

df <- data.frame(x = c(0,0,1,2,2,2))

ggplot(df,aes(x)) +
geom_histogram(binwidth=1) +
scale_x_continuous(breaks=0:2)


This is what it looks so far - the left side of a bar is on top of the label:

enter image description here

Is it possible to adjust the given snippet in such a way? (without using geom_bar instead f.x.)

Answer

This doesn't require a categorical x axis, but you'll want to play a little if you have different bin widths than 1.

library(ggplot2)

df <- data.frame(x = c(0,0,1,2,2,2))

ggplot(df,aes(x)) + 
geom_histogram(binwidth=1, origin = -0.5) + 
scale_x_continuous(breaks=0:2)