组合geom_rect和geom_line

问题描述 投票:0回答:1

我在 geom_rect 函数中遇到 aes(xmin, xmax, fill) 问题。如何使用 geom_rect 添加 event_type ?这是我的虚拟前任

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()
r ggplot2
1个回答
0
投票

也许这就是您试图用代码实现的目标。

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 (%)"
  )+
  theme_minimal()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.