Using geom_rect() to add a drought event to ggplot

Today I spent a couple of hours trying to sort out how to add shading to a ggplot2 line graph in R to define the Millennial drought in SE Australia. Stumbled across geom_rect() and after a bit of trawling through various internet forums got it up and going! More or less happy with the result.

I’m also trying to improve my code commenting, so I don’t need to spend hours figuring out what I did last time.

R is a powerful, but challenging tool, and it’s always nice when something works out, see the script below!

ggplot_event_2

setwd(“your_working_directory”)
library(ggplot2)
library(scales)

data = read.csv(“data.csv”, header = T)

##This data set had two columns, Date (dd/mm/yyyy) and Modelled Discharge

##Assigning data to variables
x <- data$Date
Qmod <- data$QM

##Correct date format
Date2 <- data$Date2 <- as.Date(as.character(data$Date),format=”%d/%m/%Y”)

##data frame
df <- data.frame(Date2, Qmod)

##in the ggplot package
ggplot() +
##geom_rect is used to delimit an event (the Millennial Drought 2001-2009) in the graph
geom_rect(aes(xmin=c(as.Date(“2001-01-01”)),xmax=c(as.Date(“2009-12-31”)), ymin = c(-Inf), ymax = c(Inf), alpha = 0.1)) +
##geom_line plots discharge over time
geom_line(data = df, aes(x = Date2, y = Qmod, colour = “Qmod”), size = 0.8) +
scale_colour_manual(“”,
breaks = c(“Qmod”),
values = c(“#666666”)) +
labs(x = “Date (Year)”, y = “Discharge (Drips/Day)”) +
theme(axis.title.x = element_text(size = 14),
axis.title.y = element_text(size = 14, vjust=1.5)) +
theme_bw() +
scale_x_date(breaks = “5 years”, labels = date_format(“%Y”)) +
theme(legend.position = “none”)

##to save!
ggsave(“NAME.eps”, width = 15, height = 10, dpi = 800, units = c(“cm”))

Leave a comment