2017-05-08 115 views
0

我正在試圖製作兩個數據集的一個圖來比較它們的值。將兩個圖組合成一個

ggplot() 
ggplot(pos_plot, aes(x=WORD, y=FREQ)) + 
    geom_bar(position="dodge", colour="blue", stat = "identity") + 
ggplot(neg_plot, aes(x=WORD, y=FREQ)) + 
    geom_bar(position="dodge", colour="red", stat = "identity") 

但是當我運行這段代碼我得到的錯誤:

Error: Don't know how to add o to a plot 

有誰知道我做錯了嗎?

+1

這將是更容易,如果你合併做兩個數據集合爲一個並創建一個識別源數據集的因子。然後你可以使用'facet.grid'來形成一個diptych,或者使用'fill = [factor id'source']來將它們在一個繪圖中進行比較。 – ulfelder

+0

你想如何結合這兩個地塊?兩個並排的情節,或一個情節與並排的酒吧? –

回答

0

您顯然需要更多地研究圖形的語法。 ggplot中的+登錄不能用於在您的圖中添加另一個ggplot。你可以使用facet_grid由@ulfelder在評論中提到的,或grid.arrangegridExtra包:

require(ggplot2) 
library(gridExtra) 
library(grid) 

dfpos <- data.frame(x=1,y=1) 
dfneg <- data.frame(x=-1,y=-1) 

ppos <- ggplot(dfpos, aes(x,y)) + geom_point() 
pneg <- ggplot(dfneg, aes(x,y)) + geom_point() 

grid.arrange(ppos,pneg) 

或者重寫自己的代碼:

ppos <- ggplot(pos_plot, aes(x=WORD, y=FREQ)) + 
     geom_bar(position="dodge", colour="blue", stat = "identity") 
pneg <- ggplot(neg_plot, aes(x=WORD, y=FREQ)) + 
     geom_bar(position="dodge", colour="red", stat = "identity") 
grid.arrange(ppos,pneg)