2014-12-05 93 views
0

如何創建一個自定義圖例來指示星期天是紅色的(在星期一旁邊有一個紅色框,星期二是藍色?以下是我的MWE。需要的是代碼,使傳說。如何將圖例添加到基於陰影顏色的R陰謀

library(ggplot2) 
library(scales) 
set.seed(1) 
data <- data.frame(Date = seq(as.Date('2000-01-01'), 
       len= 23, by="1 day"), 
       Value = sample(1:50, 23, replace=TRUE)) 
sunday <- data.frame(date = seq(as.Date('2000-01-01 12:00:00'), len = 4, by="7 days")) 
monday <- data.frame(date = seq(as.Date('2000-01-02 12:00:00'), len = 4, by="7 days")) 
ggplot() + geom_line(data = data, aes(x = Date, y = Value)) + 
    geom_rect(data = sunday, aes(xmin = date-.5, xmax = date+.5, ymin = -Inf, ymax = Inf), alpha = 0.4, fill="red") + 
    geom_rect(data = monday, aes(xmin = date-.5, xmax = date+.5, ymin = -Inf, ymax = Inf), alpha = 0.4, fill="blue") + 
    scale_x_date(breaks = date_breaks("1 day"), labels = date_format("%d")) 

enter image description here

+1

使用 「傳奇」 的設施並沒有真正意義。您需要構建反映這些矩形顏色的註記結構。 – 2014-12-05 03:47:30

+1

我有點困惑。 2000-01-01實際上是星期六。我在這裏錯過了什麼嗎? – jazzurro 2014-12-05 03:55:48

+0

是的,我的情節在這方面是不正確的。爲了說明真正的問題是什麼 - 如何獲得一個圖例(或者註解結構可能會起作用),我只是把它作爲一個假的例子扔在一起。 – bill999 2014-12-05 03:57:25

回答

3

鑑於上述評論,我有周六和週日在這裏,我結合這兩個數據幀和創建含當天(即週六和週日列)。我在fillgeom_rect中使用了這一列,通過這種方式可以看到一個圖例

library(ggplot2) 
library(scale) 
library(dplyr) 

set.seed(1) 
data <- data.frame(Date = seq(as.Date('2000-01-01'), 
      len= 23, by="1 day"), 
      Value = sample(1:50, 23, replace=TRUE)) 

saturday <- data.frame(date = seq(as.Date('2000-01-01 12:00:00'), len = 4, by="7 days")) 
sunday <- data.frame(date = seq(as.Date('2000-01-02 12:00:00'), len = 4, by="7 days")) 

# Combine Saturday and Sunday data. If you use lubridate, there will be better way of 
# doing this kind. But, for this demonstration, I chose this way. 

combined <- mutate(rbind_list(saturday, sunday), 
        day = rep(c("Saturday", "Sunday"), each = 4)) 

ggplot() + geom_line(data = data, aes(x = Date, y = Value)) + 
geom_rect(data = combined, aes(xmin = date-.5, xmax = date+.5, 
      ymin = -Inf, ymax = Inf, fill = day), alpha = 0.4) + 
scale_fill_manual(values = c("red", "blue")) + 
scale_x_date(breaks = date_breaks("1 day"), labels = date_format("%d")) 

enter image description here

+0

工程就像一個魅力。非常感激。 – bill999 2014-12-05 04:20:21

+1

@ bill999快樂,夥伴。 :) – jazzurro 2014-12-05 04:24:26