Histogram with spaces using continuous data (width

2019-08-03 17:02发布

问题:

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)

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)

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

回答1:

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)


标签: r plot ggplot2