1

I'm trying to plot a histogram using ggplot which has some space between the bars.

This is no problem with discrete data:

b= data.frame(x=sample(LETTERS[1:3],size=50, replace=T))
ggplot(b, aes(x=x)) + geom_bar(width=.3)

enter image description here However, using continuous data, width seems to have no effect.

a= data.frame(x=rnorm(100))
ggplot(a, aes(x=x, width=.5)) +
geom_bar(width=.3, binwidth=1)

continuous histogram

How can a histogram with spaced bars be archived for continuous data?

akraf
  • 2,965
  • 20
  • 44

1 Answers1

2

I think doing this is a really bad idea (and ggplot2 doesn't support it).

Here is one possibility:

breaks <- pretty(range(a$x), n = 6, min.n = 1)
mids <- 0.5 * (breaks[-1L] + breaks[-length(breaks)])

ggplot(a, aes(x = cut(x, breaks = breaks, labels = mids))) + 
    geom_bar(width=.3)
Roland
  • 127,288
  • 10
  • 191
  • 288
  • 1
    +1 for 'it's a bad idea.' For that matter, a histogram by definition quantizes data into subsets, so 'continuous' makes no sense. – Carl Witthoft Jan 21 '15 at 12:39
  • @Roland, Carl I want to do this for showing histograms of two subsets of the same data, placing their bars side-by-side (dodge). By using space, I tried to make it easier to see, which pair of bars belong to which group and to see which bars are pairs anyway. If you have other suggestions, I'd be glad to learn – akraf Jan 21 '15 at 12:58
  • 1
    @akraf Just set a `fill` colour. – Roland Jan 21 '15 at 13:03
  • sorry for using "groups" unclearly. I'm using fill colors but this gives me a "zebra" pattern on the screen and its hard to distinguish pairs of bars (belonging to different groups but to the same bin). So I tried to use space to alleviate. But I'll give facetting a try too. Thanks. – akraf Jan 21 '15 at 13:18
  • 2
    Yes, facetting is the best way to do this. – Roland Jan 21 '15 at 13:26