Display a rectangle in ggplot with x axis in date format

前端 未结 1 1830
庸人自扰
庸人自扰 2021-01-18 14:32

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 = \"bl         


        
相关标签:
1条回答
  • 2021-01-18 15:10
    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)
    

    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)
    
    0 讨论(0)
提交回复
热议问题