Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Time series plot with event annotations using geom_rect

I have problem with aes(xmin, xmax, fill) in geom_rect function. How to add event_type with geom_rect ? Here is my dummy example.

dummy <- data.frame(Date = seq(as.Date("1981-01-01"), as.Date("2010-12-01"), by = "month"),
                    Percentage = runif(360, min = 0, max = 100))
dummy$Year <- format(dummy$Date,"%Y")
# Define El Niño, La Niña, and neutral years
el_nino_years <- c(1982, 1987, 1991, 1994, 1997, 2002, 2004, 2009)
la_nina_years <- c(1984, 1988, 1995, 1999, 2000, 2007, 2010)
neutral_years <- setdiff(1981:2010, c(el_nino_years, la_nina_years))
# Create a new column based on the occurrence of El Niño, La Niña, or neutral years
dummy <- dummy %>%
  mutate(event_type = case_when(
    Year %in% el_nino_years ~ "El Niño",
    Year %in% la_nina_years ~ "La Niña",
    Year %in% neutral_years ~ "Neutral",
    TRUE ~ NA_character_  # For years outside the specified range
  ))
dummy_plot <-  ggplot(data = dummy,
      aes(x= Date, y= Percentage))+
  geom_line()+
  labs(
    x = " ",
    y = "Area (%)"
  )+
  theme_minimal()

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Maybe this is the plot you were trying to create with your code.

library(ggplot2)
library(dplyr)

df_rect <- dummy %>%
  group_by(Year) %>%
  summarize(x1=first(Date), x2=last(Date), event_type=first(event_type))

dummy_plot <-  ggplot(data=dummy, aes(x=Date, y=Percentage))+
  geom_line() +
  geom_rect(aes(xmin=x1, xmax=x2, fill=event_type), 
            ymin=min(dummy$Percentage), ymax=max(dummy$Percentage), 
            alpha=0.2, data=df_rect, inherit.aes=F)+
  scale_x_date(date_breaks = "1 year", date_labels = "%Y") +
  labs(x=" ",  y="Area (%)") +
  coord_cartesian(expand=F) +
  theme_minimal() %+replace% theme(legend.position="bottom")

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading