2015-11-19 32 views
1

不好意思再次打擾你們,但是我正在爲一個簡單的任務苦苦掙扎,在尋找解決方案和瀏覽互聯網之後,我無法整理出來。 這裏的交易。我有三個陣列r中多層數據框的堆積條形圖

c1 <- data.frame(cf=rep(100,10),m=seq(1,10,1)) 
c1$cf[10] <- 500 

c2 <- data.frame(cf=rep(50,10),m=seq(1,20,2)) 
c2$cf[10] <- 650 

c3 <- data.frame(cf=rep(150,5),m=seq(1,20,4)) 
c3$cf[5] <- 450 

和我想沿X創建與來自1的序列的堆積條形圖到20(三個第二列的所有可能的條目)和的(可能)總和y三列第一列。

我試圖合併的3個數據幀

m <- merge(c1,c2,by="m",all=TRUE) 
m <- merge(m,c3,by="m",all=TRUE) 

我融化它

m1 <- melt(m,id="m") 
m1 <- na.exclude(m1) 

,並試圖用ggplot作爲

ggplot(data=m1,aes(x=m,y=value,fill=row)) 

但我不買東西仍然不知道如何以正確的方式顯示條形圖,如果這是做我想獲得的正確方法。

萬一,非常感謝您的幫助。

+0

您將需要包括您嘗試過或沒有工作的內容,以便任何人解釋*爲什麼*它不起作用。另外,上面的代碼無效 - a < - data.frame(...)+ c < - d。用'+'表示';'?由於您已經瀏覽過互聯網,您可能想指出您嘗試過的解決方案,以及您找到的資源。 –

回答

3

首先,讓我們看看你的數據:

head(m1) 
# m variable value 
# 1 1  cf.x 100 
# 2 2  cf.x 100 
# 3 3  cf.x 100 
# 4 4  cf.x 100 
# 5 5  cf.x 100 
# 6 6  cf.x 100 

看起來不錯。現在讓我們看看你的繪圖命令:

ggplot(data=m1,aes(x=m,y=value,fill=row)) 

兩個問題:首先,引用你的數據上面沒有列叫做「行」。我假設你想要基於名爲「變量」的列的​​填充顏色:

ggplot(data = m1, aes(x = m, y = value, fill = variable)) 
# Error: No layers in plot 

二,什麼類型的情節?吧情節?散點圖?箱形圖?你需要告訴ggplot要繪製什麼。這是什麼錯誤信息告訴你 - 你提供的數據,但沒有指示什麼來繪製。這在ggplot2的任何介紹中都有介紹。

ggplot(data = m1, aes(x = m, y = value, fill = variable)) + 
    geom_bar() 

但現在我們得到另一個錯誤:

Error : 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. (Defunct; last used in version 0.9.2)

這是一個有用的錯誤,最好的一種! 如果您希望y代表數據中的值,請使用stat =「identity」。

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

它的工作原理。

+0

我真的很感謝你!我可以得到最好的幫助!還有一個問題。爲了得到這個結果,從我的三個數據框開始,是否有更好的過程?或者我真的不得不合並之前,融化並排除NA值?再次感謝 – Stefano

+0

這絕對是不錯的。使用1個數據幀比使用3更容易,並且長格式數據總是被ggplot2優先使用。您可以閱讀[整潔數據文件](https://www.google.com/url?sa=t&rct=j&q=&esrc=s&source=web&cd=3&cad=rja&uact=8&ved=0ahUKEwinn6uO-abJAhWUU4gKHaDuBCMQFggmMAI&url=http%3A%2F %2Fvita.had.co.nz%2Fpapers%2Ftidy-data.pdf&USG = AFQjCNFUAQr-w_87XpPhfEDoDYQw5-G5zg&SIG2 = WuLdOUDHPBJAmGLo-94PiA)。這是一個非常快速的閱讀,可以幫助學習如何思考這樣的問題。 – Gregor

+0

我不知道該如何謝謝你! – Stefano