Histogram with spaces using continuous data (width

2019-08-03 16:33发布

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?

标签: r plot ggplot2
1条回答
三岁会撩人
2楼-- · 2019-08-03 17:27

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)
查看更多
登录 后发表回答