2016-11-16 46 views
0

可以說我有堆疊barplot象下面這樣:- [R GGPLOT2:使用定製的間隙分組杆

library(ggplot2) 
dfr <- data.frame(x=1:5,y=c(4,6,2,3,6,8,3,6,8,4), 
     z=c("A","A","A","A","A","B","B","B","B","B")) 

ggplot(dfr,aes(x=x,y=y,fill=z))+ 
    geom_bar(stat="identity") 

barplot

我想組1和2一起,和組3,4,5一起。我的想法是在2和3之間有更大的差距。是否可以通過像c(2,4,2,2)這樣的自定義間隙向量來填補空白。我不想爲此目的使用faceting。

+1

一個權宜的解決辦法是增加高度0的酒吧,在那裏你需要的空間,這裏提到: http://stackoverflow.com/questions/30100500/specific-spaces -bar-plot-in-a-barplot-ggplot2-r – shreyasgm

+0

請參閱[這裏](http://stackoverflow.com/questions/37795648/r-ggplot2-barplot-partial-semi-stack?noredirect=1&lq=1)和其中的鏈接。 – Henrik

回答

0

這是一個黑客,但會得到您想要的結果。

library(ggplot2) 
dfr <- data.frame(x=1:5,y=c(4,6,2,3,6,8,3,6,8,4), 
     z=c("A","A","A","A","A","B","B","B","B","B")) 
dfr$x2 <- ifelse(dfr$x %in% 1:2, dfr$x, dfr$x+1) 

ggplot(dfr,aes(x=x2,y=y,fill=z))+ 
    geom_bar(stat="identity") + 
    scale_x_continuous("x", breaks = c(1, 2, 4, 5, 6), labels = seq(1:5)) 

enter image description here