2016-06-13 88 views
2

我有一個barplot的情況,我希望一些層次被堆疊和一些躲閃。這可能嗎?這是一個工作示例。R ggplot2:Barplot部分/半堆棧

library(ggplot2) 
library(reshape) 

dat <- data.frame(name=c("a","b","c","d"), 
      full=c(124,155,122,145), 
      parta=c(86,72,40,26), 
      partb=c(38,83,82,119)) 

dat1 <- reshape::melt(dat,id.vars=c("name")) 

#stack 
ggplot(dat1,aes(x=name,y=value,group=variable,fill=variable))+ 
    geom_bar(stat="identity",position="stack")+ 
    ggtitle("stack") 

#dodge 
ggplot(dat1,aes(x=name,y=value,group=variable,fill=variable))+ 
    geom_bar(stat="identity",position="dodge")+ 
    ggtitle("dodge") 

partial-stack

在上述例子中,圖1和圖2(左)是標準barplots。圖3被修改爲我正在尋找的內容。我想要'完整'級別保持'閃避',而'parta'和'partb'要堆疊在一起。

這是一個虛擬的例子。但是,實際使用是當我想顯示某個東西的完整值時,然後顯示如何分解成子組件。上面的例子是一個單獨的分割。也許人們可能想要展示多個分割。見下圖。

split

紅是由一定量的藍色和綠色的。綠色還包含一定量的黃色和粉紅色。也許有更好的方法來做到這一點。

+0

如果A部分和B部分總是等於滿,爲什麼不乾脆堆A和B? – Nate

+0

確實。編輯解釋更多一點。 – rmf

+1

相關:[here](http://stackoverflow.com/questions/9493159/staggered-and-stacked-geom-bar-in-the-same-figure),[here](http://stackoverflow.com/問題/ 12715635/ggplot2-bar-plot-with-stack-and-dodge)和[here](https://stat.ethz.ch/pipermail/r-help/2008-October/177932.html) – Henrik

回答

2

這是你想要的嗎?我改編自@Henrik指出的鏈接。

# 1st layer 
g1 <- ggplot(dat1 %>% filter(variable == "full"), 
      aes(x=as.numeric(name) - 0.15, weight=value, fill=variable)) + 
    geom_bar(position="identity", width=0.3) + 
    scale_x_continuous(breaks=c(1, 2, 3, 4), labels=unique(dat1$name)) + 
    labs(x="name") 

# 2nd layer 
g1 + geom_bar(data=dat1 %>% filter(grepl("part", variable)), 
       aes(x=as.numeric(name) + 0.15, fill=variable), 
       position="stack", width=0.3) 

enter image description here