同一图上的多个图使用R中ggplot的facet_wrap功能?

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

我正在尝试在具有这些位置统计信息的图形上方添加特定年份的累计值。以下是示例代码(摘自我先前的问题之一的解决方案建议)。

library(tidyverse)
library(lubridate)
library(dplyr)
library(tidyr)

mydate <- as.data.frame(seq(as.Date("2000-01-01"), to= as.Date("2019-12-31"), by="day"))
    colnames(mydate) <- "Date"
    Data <- data.frame(A = runif(7305,0,10), 
                       J = runif(7305,0,8), 
                       X = runif(7305,0,12), 
                       Z = runif(7305,0,10))

    DF <- data.frame(mydate, Data)

    Data_Statistics <- DF %>% mutate(Year = year(Date), Month = month(Date)) %>%
      pivot_longer(-c(Date,Year,Month), names_to = "variable", values_to = "values") %>% 
      filter(between(Month,5,10)) %>% 
      group_by(Year, variable) %>% 
      mutate(Cumulative = cumsum(values)) %>%
      mutate(NewDate = ymd(paste("2020", Month,day(Date), sep = "-"))) %>%
      ungroup() %>%
      group_by(variable, NewDate) %>%
      summarise(Median = median(Cumulative),
                Maximum = max(Cumulative),
                Minimum = min(Cumulative),
                Upper = quantile(Cumulative,0.75),
                Lower = quantile(Cumulative, 0.25))

我想从2019中提取Data_Statistics年的数据,但是没有做。我不希望获得2019年的统计数据,而是在我感兴趣的时期(5月至10月,其中第5个月-10)

 Data_2019 <- DF %>% mutate(Year = year(Date), Month = month(Date)) %>%
  pivot_longer(-c(Date,Year,Month), names_to = "variable", values_to = "values") %>% 
  filter(between(Month,5,10)) %>%
  filter(Year == 2019) %>% 
  group_by(Year, variable) %>% 
  mutate(Cumulative = cumsum(values)) 

使用以下示例代码使用Data_Statisticsfacet_wrap功能绘制ggplot给我附上了附图。

Data_Statistics %>% pivot_longer(cols = c(Median, Minimum,Maximum), names_to = "Statistic",values_to = "Value") %>%
  ggplot(aes(x = NewDate))+
  geom_ribbon(aes(ymin = Lower, ymax = Upper, fill = "Upper / Lower"), alpha =0.5)+
  geom_line(aes(y = Value, color = Statistic, linetype = Statistic, size = Statistic))+
  facet_wrap(~variable, scales = "free")+
  scale_x_date(date_labels = "%b", date_breaks = "month", name = "Month")+
  ylab("Daily Cumulative Precipitation (mm)")+
  scale_size_manual(values = c(1.5,1,1.5))+
  scale_linetype_manual(values = c("dashed","solid","dashed"))+
  scale_color_manual(values = c("red","darkblue","black"))+
  scale_fill_manual(values = "cyan", name = "")

enter image description here

我的最终目标

我想在其各自的facets(即另一个geom_line)的数据上方添加2019年的数据,以查看与前几年的统计数据相比我们所拥有的。谢谢。

r ggplot2 plot filter facet-wrap
1个回答
1
投票

[如果要用2019年数据覆盖每个方面,请向ggplot中添加新的geom_line函数。您需要先像对待总数据一样先处理2019年数据:

Data_2019_plot <- Data_2019  %>% 
  pivot_longer(cols = c(Median, Minimum,Maximum), names_to = "Statistic",values_to = "Value")

现在在ggplot序列的末尾添加

+ geom_line(data = Data_2019_plot, 
            aes(y = Value, color = Statistic, linetype = Statistic, size = Statistic))

您会得到以下情节:enter image description here

[与您的样本数据一起,2019年的行有很多重叠,因此它们看起来不太清晰。您可能要为2019年设置特定的颜色,而不是将其设置为美观的贴图。

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