2014-01-06 64 views
13

我有一張桌子,我想用ggplot2製作一個情節,到目前爲止我一直沒有成功。 我已經準備了一個簡化的表看起來像這樣Barplot在R/ggplot有多種因素

df1<-data.frame(Loc=c(rep("L1",5),rep("L2",3),rep("L3",4)), 
Type=c(rep("T1",3),rep("T2",2),"T1","T2","T2","T1","T1","T2","T2"), 
     y2009=rep("A",12),y2010=c("A","B","A","A","A","A","B","B","A","A","B","B"), 
     y2011=c("B","B","B","A","B",rep("B",4),"A","B","B")) 
df1 

祿具有3 locations.Each位置有2種樣品T1或T2的。他們開始在2009年爲A,隨着時間的推移變得有些B.因此,到2011年,有很多B.

這是數字我至今

ggplot(df1,aes(x=Type)) + geom_bar()+facet_grid(~Loc) 
ggplot(df1,aes(x=y2009,fill=Type)) + geom_bar(position="dodge")+facet_grid(~Loc) 

enter image description here enter image description here

我不太清楚如何從三個因素中得出結論。

我想要一個類似於下圖的數字,我大致在塗料中起草。這些方面是位置,我只用Loc1作爲例子。 enter image description here

+0

這將幫助你開始http://www.cookbook-r.com/Graphs/,並且你可能對堆積的情節和方面感興趣,特別是/ –

+0

你幾乎在那裏,從「熔化」看'reshape2' – Ananta

+0

嗯..表格中的所有列都是因素。融化是否會對因素產生影響?我認爲它只是做了一些事情,如果一列有數字或整數存在。 – rmf

回答

14

嘗試多層次的方面:

df2 <- melt(df1, id.vars=c("Loc", "Type")) 
ggplot(data=df2, aes(x=value, fill=Type)) + 
    geom_bar() + facet_wrap(~ Loc + variable, nrow=1) 

enter image description here

或者,facet_grid,我覺得看起來更好,但不完全匹配您的草圖:

df2 <- melt(df1, id.vars=c("Loc", "Type")) 
ggplot(data=df2, aes(x=value, fill=Type)) + 
    geom_bar() + facet_grid(Loc ~ variable) 

enter image description here

最後,借用from this post,你可以嘗試更好地辨別顏色的位置(顯然配色方案可以使用一些工作,但你明白了吧):

df2 <- melt(df1, id.vars=c("Loc", "Type")) 
ggplot(data=df2, aes(x=value, fill=Type)) + 
    geom_rect(aes(fill=Loc),xmin =-Inf,xmax=Inf,ymin=-Inf,ymax=Inf,alpha = 0.1) + 
    geom_bar() + 
    facet_wrap(~ Loc + variable, nrow=1) 

enter image description here

如果你想實際每個位置都有獨立的面板,我想你必須使用自己的網格視口和grobs。有一個包ggextra這樣做的東西,但它似乎不可用於最新的R版本。