2011-07-14 151 views
8

我在ggplot2中製作堆疊條形圖時遇到了一些問題。我知道如何用barplot()創建一個,但是我想使用ggplot2,因爲它很容易讓bar具有相同的高度('position ='fill'',如果我沒有弄錯的話)。爲多個變量製作堆疊條形圖 - g中的ggplot2

我的問題是,我有多個變量,我想繪製在彼此的頂部;我的數據看起來像這樣:

dfr <- data.frame(
    V1 = c(0.1, 0.2, 0.3), 
    V2 = c(0.2, 0.3, 0.2), 
    V3 = c(0.3, 0.6, 0.5), 
    V4 = c(0.5, 0.1, 0.7), 
    row.names = LETTERS[1:3] 
) 

我想是與類別的曲線A,B,和C在X軸上,並且對於每個那些,對於V1,V2,V3和V4堆疊的值在Y軸上彼此重疊。我所看到的大多數圖表在Y軸上只繪製了一個變量,但我確信某人可以以某種方式做到這一點。

我怎樣才能做到這一點與ggplot2?謝謝!

+0

+1用於添加樣本數據。歡迎來到SO。 – Andrie

+0

如果您發現任何有用的答案,請選擇一個作爲您接受的答案。 –

回答

15

首先進行一些數據操作。將類別添加爲變量並將數據融化爲長格式。

dfr$category <- row.names(dfr) 
mdfr <- melt(dfr, id.vars = "category") 

現在的情節,使用命名variable來確定每個欄的填充顏色的變量。

library(scales) 
(p <- ggplot(mdfr, aes(category, value, fill = variable)) + 
    geom_bar(position = "fill", stat = "identity") + 
    scale_y_continuous(labels = percent) 
) 

(編輯:代碼更新爲使用scales軟件包,因爲GGPLOT2 V0.9根據需要)

enter image description here

+0

+1當我剛剛發佈相同的內容時,你就擊敗了! –

+0

@lselzer,偉大的思想家一樣思考!國際海事組織,下一次,你應該毫不猶豫地發佈你的答案,即使非常相似。 –

+0

非常感謝Richie!這對我有用。我有一個問題,但如果我用'p < - ggplot(mdfr,aes(category,value,fill = variable,position ='fill'))+ + geom_bar()'杆不向上延伸以具有相同的高度。爲了讓情節做到這一點,我需要做其他事嗎?謝謝! – Annemarie

3

請原諒我開始一個新的答案,而我真的只是想添加一個評論@Richie提供的美麗解決方案。我沒有最小的點發表評論,所以這裏是我的情況:

... + geom_bar(position="fill")爲我的繪圖拋出一個錯誤,我使用的ggplot2版本0.9.3.1。並重塑2,而不是重塑融化。

error_message: 
*Mapping a variable to y and also using stat="bin". 
    With stat="bin", it will attempt to set the y value to the count of cases in each group. 
    This can result in unexpected behavior and will not be allowed in a future version of ggplot2. 
    If you want y to represent counts of cases, use stat="bin" and don't map a variable to y. 
    If you want y to represent values in the data, use stat="identity". 
    See ?geom_bar for examples. (Deprecated; last used in version 0.9.2) 
stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this. 
Error in pmin(y, 0) : object 'y' not found* 

所以我將它改爲geom_bar(stat='identity'),它工作。

+0

感謝您發表這個消息,我無法弄清楚如何解決這個錯誤! –

相關問題