Home > Mobile >  How do I change the colors of my background based on time of day in x-axis on a 24 hour basis?
How do I change the colors of my background based on time of day in x-axis on a 24 hour basis?

Time:05-21

hour_mark   avg_intensity
<int>   <dbl>
0   2.1295503
1   1.4190782
2   1.0439443
3   0.4437299
4   0.6330472
5   4.9506438
6   7.7712137
7   10.7336198
8   14.6680988
9   15.3877551
10  17.6437029
11  16.9212513
12  19.8470716
13  18.7752443
14  18.8686211
15  15.5846995
16  17.7166483
17  21.6556291
18  21.9216336
19  21.3852097
20  14.3399558
21  12.0729282
22  9.0630531
23  4.9966777
ggplot(data=avg_int_hourly,
    aes(x=factor(hour_mark),
        y=avg_intensity,group=1)) 
    geom_line(color="red") 
    geom_point() 
    labs(title='Average Intensity Each Hour of the Day') 
    xlab('Hours of Day') 
    ylab('Average Intensity')

enter image description here

Nothing wrong with my graph above but now I want to change the color of the background based on time of day: 0-6 = Purple, 6-19 = Orange, 20-23 = Purple

So, I want it to look something like (being able to adjust opacity is necessary for me as well): enter image description here

And if possible, I hope there's a way to add the legends of the two differing colors to note that they represent night and day to the right or the top of the graph.

I've tried something like this but I have no idea what I'm doing:

enter image description here

CodePudding user response:

We could use geom_rect:

library(tidyverse)
library(scales)

ggplot(data=avg_int_hourly,
       aes(x=factor(hour_mark),
           y=avg_intensity,group=1)) 
  geom_line(color="red") 
  geom_point() 
  geom_rect(aes(xmin=0,xmax=7,ymin=0,ymax=Inf),fill="blueviolet",alpha=0.05) 
  geom_rect(aes(xmin=7,xmax=21,ymin=0,ymax=Inf),fill="pink",alpha=0.05) 
  geom_rect(aes(xmin=21,xmax=24,ymin=0,ymax=Inf),fill="blueviolet",alpha=0.05) 
  labs(title='Average Intensity Each Hour of the Day') 
  xlab('Hours of Day') 
  ylab('Average Intensity') 
  theme_minimal()

enter image description here

  • Related