bill999
bill999

Reputation: 2529

How to add legend to R plot based on shade color

How do I create a custom legend that indicates Sunday is red (have a red box next to the word "Monday" and Tuesday is blue? Following is my MWE. All it needs is code to make the legend.

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

Upvotes: 0

Views: 1619

Answers (1)

jazzurro
jazzurro

Reputation: 23574

Given the comments above, I have Saturday and Sunday here. I combined the two data frames and created a column including day (i.e., Saturday and Sunday). I used this column for fill in geom_rect. In this way, you can see a legend.

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

Upvotes: 3

Related Questions