2014-09-27 68 views
0

我想建立一個堆積條形圖,在字段fill提供的數值而不是類別。ggplot - 使用數值填充堆積的條形圖

這是我的圖表到目前爲止:

graph

ggplot example用於堆積條形圖,該字段fill對應diamonds數據集的列cut。 此列對應:

> class(diamonds$cut) 
[1] "ordered" "factor" 

因此,我認爲,不同的術語

> head(diamonds$cut) 
[1] Ideal  Premium Good  Premium Good  Very Good 
Levels: Fair < Good < Very Good < Premium < Ideal 

的頻被計算並用於填充條。

ggplot stacked bar chart

在我的情況我有兩個類型的值形成的(在我的數據幀tot)顯示在X條中的每個值:updown。這些對應於列在我的數據幀:

> head(cyt.4) 
                  COG tot up down 
1       [C] Energy production and conversion 17 16 1 
2 [D] Cell cycle control, cell division, chromosome partitioning 0 0 0 
3      [E] Amino acid transport and metabolism 34 30 4 
4      [F] Nucleotide transport and metabolism 11 9 2 
5      [G] Carbohydrate transport and metabolism 13 9 4 
6       [H] Coenzyme transport and metabolism 3 3 0 

例如具有X杆(tot)的10值,可以在up = 7分,down = 3。現在,假設我將紅色分配給up,並將綠色分配給down,我希望我的酒吧可以填充70%(10箇中的7個)紅色和30%綠色(3個10)。

我一直在掙扎幾天,我沒有得到任何有效的結果。

回答

2

將數據從「寬」轉換爲「長」格式,例如使用reshape包。然後在ggplot中變得更容易。重組的數據幀包含值爲「下」和「上」的variable。這可以作爲有序或無序因子給予fill=

下面是一個小例子,模仿你的數據:

library(ggplot2) 
library(reshape) 

x <- c(14,11,9,17) 
dfr <- data.frame(COG=letters[1:4], down=1:4, up=x-1:4, tot=x) 
dfr <- melt(dfr[,-4], idvar="COG") 

ggplot(dfr, aes(x=COG, y=value, fill=factor(variable))) + 
    geom_bar(stat="identity") + 
    coord_flip() + 
    scale_fill_manual(values=c("green3","red3")) 

enter image description here

乾杯!

編輯:如果水平在您的數據集中混在一起,那是因爲factor在找到它的順序中創建了因子水平。要更改訂單,請對數據集進行重新排序(與我一樣),並讓melt負責它,或者保留它並使用ordered使該因子按照您指定的順序執行。

+0

這很好,但我不能讓它工作。我的命令如下:'> colnames(cyt.4) [1]「cyt.4」「variable」「value」 > ggplot(cyt.4,aes(x = COG,y = value,fill = factor變量)))+ + geom_bar(STAT = 「同一性」)+ + coord_flip()+ + scale_fill_manual(值= C( 「green3」, 「RED3」)) 錯誤:美學必須是長度之一,或與dataProblems:COG'的長度相同。我認爲我得到這個錯誤是因爲矢量「因素(變量)」不具有相同長度的「COG」。我做錯了什麼? – efrem 2014-09-28 08:23:45

+0

愚蠢的我!列名中出現錯誤!你的提示很棒!謝謝! – efrem 2014-09-28 10:26:38