2012-10-03 54 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绘制而不是绘图。 –