Home > OS >  Background bars in ggplot2 using geom_rect
Background bars in ggplot2 using geom_rect

Time:04-05

I have daily flow data in a dataset I've called "dat1_na".

It spans between ~1940 and ~2020 so there's 18,780 lines in this dataset.

str(dat1_na) is:

'data.frame':   18780 obs. of  9 variables:
 ...
 $ MLd    : num  96 34 34 20 34 34 52 34 34 26 ...
 $ Date   : Date, format: "1943-09-19" "1943-09-07" "1943-09-08" "1943-09-11" ...
 ...
 $ Climate: chr  "Dry" "Dry" "Dry" "Dry" ...

So it's a simple Line graph (hydrograph) showing MLd (the daily flow rate) against time which is no problem. However, I'm trying to shade the background using geom_rect according to the 'Climate' part of the dataset which only has 2 possible values: "Dry" and "Wet". The issue is that I can't get the background to show up properly. I know the data is being read right because if I tweak my code a bit I can see the dry years and wet years where they should be:

ggplot(dat1_na, aes(x=Date, y=MLd, xmin=Date, xmax=Date, ymin=0, ymax=6000))   
  geom_line(colour = "#231EDC")   
  geom_rect(aes(colour=Climate), alpha=0.2)  
  theme_minimal() 

enter image description here

  • Related