2014-03-05 86 views
0

我試圖做一個堆疊條形圖具有下列數據框:堆疊條形圖與ggplot

totalleft 
     1S 2S 3S 4S 12S 25S  tests 
A-000 5 0 10 10 0 NA  A-000 
A-001 10 8 10 NA NA NA  A-001 
A-002 5 3 10 10 10 NA  A-002 
A-003 2 0 10 9 0 10  A-003 
A-004 5 4 10 10 10 NA  A-004 
A-005 5 3 10 10 10 NA  A-005 
A-006 8 7 NA 10 10 NA  A-006 
A-009 9 10 NA NA 10 10  A-009 
A-015 NA 1 NA NA NA NA  A-015 
A-016 NA 0 10 NA 6 9  A-016 
A-017 NA 0 NA NA 4 NA  A-017 
A-020 NA 1 NA NA NA NA  A-020 
A-025 NA 0 NA NA 0 NA  A-025 
A-025a NA 0 NA NA 10 NA  A-025a 
A-026 NA 9 10 NA 9 9  A-026 
A-027 NA 0 10 NA 2 9  A-027 
A-028 NA 0 NA NA 1 NA  A-028 
A-030 NA 7 NA NA 8 8  A-030 
B-000  0 0 7 8 0 0  B-000 
B-056  4 0 9 NA 0 5  B-056 
B-076  9 9 NA NA 10 10  B-076 
B-099  6 5 10 NA 5 9  B-099 
B-102  7 0 NA NA 0 10  B-102 
B-105 NA 6 NA NA NA 6  B-105 
B-119  7 8 10 10 NA NA  B-119 

然而,大多數的文件包括密謀反對兩個因素:一個是分裂沿着酒吧X軸,另一個用於分割每個小節。我的問題是如何通過因子測試將X軸分開,然後用相應的行來劃分每個柱(即1S,2S,3S,4S,12,25S)。

因此,第一個橫槓將是A-000的橫槓,其中20%是一種​​顏色(對於1S,5 /(5 + 10 + 10)),第二個40%是另一種顏色(3S,10 /(5 + 10 + 10)),最後的40%是另一種顏色(4S,10 /(5 + 10 + 10))

我使用這個命令作爲參考:

ggplot(diamonds, aes(clarity, fill=cut)) + geom_bar() 

從這個網站: http://docs.ggplot2.org/0.9.3.1/geom_bar.html#

+0

你需要將數據寫入ggplot友好。看看?熔化reshape2包 – infominer

回答

2

所以你需要重塑數據。 你想要一個堆疊的barplot,所以你需要告訴ggplot變量1S,2S ... 和測試。

#let's melt the data 
#library(reshape2) 
data.plot.m <-melt(data.plot, id.vars = "tests") #I stored your data in data.plot 
data.plot.m$variable <-gsub("X","",data.plot.m$variable) 
#as R doesn't like variable names beginning with numbers, 
#it adds an 'X' automatically when 
#we load the data with read.table so we remove this from melted data 

#now we plot the data 
ggplot(data.plot.m,aes(y = value,x = variable,fill = tests)) + 
geom_bar(stat = "identity") 

enter image description here 你會發現該地塊的順序是不同的。 我們需要重新安排你的變量:

data.plot.m$variable <- factor(data.plot.m$variable, levels = unique(data.plot.m$variable)) 
#now plot again 
ggplot(data.plot.m,aes(y = value,x = variable,fill = tests))+ 
geom_bar(stat = "identity") 

enter image description here

我才意識到你想這不是

ggplot(data.plot.m,aes(y=value,x=tests,fill=variable))+geom_bar(stat="identity") 

,並與x軸刻度標籤旋轉

ggplot(data.plot.m,aes(y=value,x=tests,fill=variable))+geom_bar(stat="identity") + theme(axis.text.x = element_text(angle=90)) 

enter image description here 請注意我如何切換x和填充

+0

啊,是的,這是非常好的,但有一件事...我們可以把X軸上的測試名稱以及1S,2S等作爲顏色? – testname123

+0

ooops掛上!我太快了!看看我的編輯 – infominer

2

這看起來像你想要的?

library(reshape2) 
library(ggplot2) 

gg <- melt(totalleft,id="tests") 
ggplot(gg) + 
    geom_bar(aes(x=tests, y=value, fill=variable), stat="identity")+ 
    theme(axis.text.x=element_text(angle=-90, vjust=.2, hjust=0)) 

melt(...)將從「寬」的格式(在不同列基團)的數據幀的「長」格式(在一個柱中(稱爲value)的所有值,和基團區分由單獨列(variable

+0

完美!謝謝! – testname123