Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display a rectangle in ggplot with x axis in date format

Tags:

date

r

ggplot2

How can I display a rectangle in ggplot with x axis in date format?

I know this code:

geom_rect(xmin = 0, xmax = 1, ymin = 0, ymax = 1,   fill = "blue")

But what if the x axis is in date format? What's the syntax for xmin and xmax? something like "2008-05-03 UTC" doesn't seem to work.

like image 667
Tony D Avatar asked Oct 18 '17 07:10

Tony D


1 Answers

set.seed(4)
df <- data.frame(date=as.Date(paste0("2017-01-", sprintf("%02d", 1:31))),
             val= sample(1:100, 31))

p <- ggplot(df, aes(date, val)) + geom_point()

p + annotate("rect",
    xmin = as.Date("2017-01-15"), xmax = as.Date("2017-01-20"), 
    ymin = -Inf, ymax = Inf,  fill = "blue", alpha=.3)

enter image description here

geom_rect would work too, but you would need to trick the code for alpha to behave, e.g.

p + geom_rect(data=df[1,], 
             aes(xmin = as.Date("2017-01-15"), xmax = as.Date("2017-01-20"),
             ymin = -Inf, ymax = Inf),  
             fill = "blue", alpha=.3)
like image 57
Adam Quek Avatar answered Oct 20 '22 10:10

Adam Quek