2012-10-03 87 views
18

我想創建一個使用ggplot2的條形圖,其中我由一個變量堆疊並由另一個閃爍。ggplot2 - 條形碼堆疊和閃避

下面是一個例子的數據集:

df=data.frame(
    year=rep(c("2010","2011"),each=4), 
    treatment=rep(c("Impact","Control")), 
    type=rep(c("Phylum1","Phylum2"),each=2), 
    total=sample(1:100,8)) 

我想創建一個barplot其中x=treatmenty=total,堆疊變量是type和迴避變量是year。當然,我可以做一個或另一個:

ggplot(df,aes(y=total,x=treatment,fill=type))+geom_bar(position="dodge",stat="identity") 

ggplot(df,aes(y=total,x=treatment,fill=year))+geom_bar(position="dodge",stat="identity") 

但不是兩個!感謝任何能提供建議的人。

+3

你只能做一個或其他,而不是兩個。看到我的相關答案在這裏:http://stackoverflow.com/questions/12592041/plotting-a-stacked-bar-plot/12592235#12592235 – Maiasaura

回答

15

這裏有一個替代使用帶小面,而不是逃避:

ggplot(df, aes(x = year, y = total, fill = type)) + 
    geom_bar(position = "stack", stat = "identity") + 
    facet_wrap(~ treatment) 

enter image description here

隨着泰勒的建議的修改:

enter image description here

+1

想要兩者的好選擇。 +1 – Maiasaura

+0

嗯,有趣的想法。我想這將不得不做!感謝@Maiasaura和Matt Parker – jslefche

+7

加上'+ theme(panel.margin = unit(-1.25,「lines」))'可以讓他們看起來更像他們在同一個視覺領域,但仍然不完全是OP在之後。尼斯最好的選擇。 +1 –

6

您可以得到的最接近的是通過在dodged四周繪製邊框來突出顯示堆積的type值。

ggplot(df, aes(treatment, total, fill = year)) + 
geom_bar(stat="identity", position="dodge", color="black") 

enter image description here

+1

嗯,邊界看起來不符合數據。例如,在運行代碼之前查看'set.seed(8)'並查看這些值。 – jslefche

+1

如果你真的很想看看,我敢打賭你可以用'geom_rect'來填充一些部分,但是你用ggplot繪製而不是繪圖。 –