如何根据阴影颜色将图例添加到R图中

时间:2014-12-05 03:36:15

标签: r plot ggplot2 legend

如何创建一个表示星期日为红色的自定义图例(“星期一”旁边有一个红色框,星期二是蓝色?以下是我的MWE。它只需要代码来制作图例。

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 个答案:

答案 0 :(得分:3)

鉴于上述评论,我周六和周日在这里。我合并了两个数据框并创建了一个包括日(即周六和周日)的列。我在fill的{​​{1}}中使用此列。通过这种方式,您可以看到一个图例。

geom_rect

enter image description here