2012-07-27 33 views
6

是否有可能與ggplot2有兩個傳說,但基於不同的數據集?例如,在下面的代碼中,我希望在同一圖形中同時顯示第一種情況的圖例和第二種情況的圖例。我的嘗試(第三種情況)不起作用。基於與ggplot2不同數據集的兩個傳說

library(ggplot2) 
library(scales) 

yrng <- range(economics$unemploy) 
xrng <- range(economics$date) 
presidential <- presidential[-(1:3), ] 

# add a fictive factor to the economics dataset 
economics <- cbind.data.frame(economics, col=gl(2, nrow(economics)/2)) 

##################### 
## first situation ## 
##################### 
# first plot with legend 
unemp <- qplot(date, unemploy, data=economics, geom="line", 
       xlab = "", ylab = "No. unemployed (1000s)", colour=col) 
# second plot without legend 
unemp + geom_vline(aes(xintercept = start), data = presidential) 

###################### 
## second situation ## 
###################### 
# first plot without legend 
unemp <- qplot(date, unemploy, data=economics, geom="line", 
       xlab = "", ylab = "No. unemployed (1000s)") 
# second plot with legend 
unemp + 
    geom_rect(aes(NULL, NULL, xmin = start, xmax = end, 
        fill = party), ymin = yrng[1], ymax = yrng[2], 
        data = presidential) + 
    scale_fill_manual(values = alpha(c("blue", "red"), 0.2)) 


##################### 
## third situation ## 
##################### 
# first plot with legend 
unemp <- qplot(date, unemploy, data=economics, geom="line", 
       xlab = "", ylab = "No. unemployed (1000s)", colour=col) 
# second plot with legend 
unemp + 
    geom_rect(aes(NULL, NULL, xmin = start, xmax = end, fill = party), ymin = yrng[1], 
       ymax = yrng[2], data = presidential) + 
    scale_fill_manual(values = alpha(c("blue", "red"), 0.2)) 

Error in data.frame(xmin = 11342, xmax = 14264, fill = "Republican", colour = function (x, : 
    arguments imply differing number of rows: 1, 0 
+1

你的代碼應該非常容易剪切並粘貼到R.就像你現在有'>'和'+'字符一樣不能實現這一點。很難看到你在做什麼。 – 2012-07-27 13:15:42

+0

@ mindless.panda這不是問題:複製代碼,然後在R控制檯中執行「僅粘貼命令」:-) – 2012-07-27 14:58:44

+0

您假設每個人都使用標準R控制檯。 =) – 2012-07-27 15:03:26

回答

13

一般而言,一旦我開始變得更復雜的情節,它幾乎總是最好停止使用qplot和使用ggplot代替。我覺得更容易去思考如何我一塊建積起片:

ggplot() + 
    geom_line(aes(x=date, y=unemploy, color=col), data=economics) + 
    geom_rect(aes(xmin=start, xmax=end, fill=party), 
      ymin = yrng[1], ymax = yrng[2], data = presidential) + 
    scale_fill_manual(values = alpha(c("blue", "red"), 0.2)) +   
    xlab("") + 
    ylab("No. unemployed (1000s)") 

這給:

plot