【问题标题】:ggplot data with missing months and blue shade for spring period in R?R中春季缺少月份和蓝色阴影的ggplot数据?
【发布时间】:2021-03-24 16:24:52
【问题描述】:

我有以下data.frame 缺少冬季月份(11 月、12 月、1 月和 2 月)。当我ggplot 数据时,即使没有冬季月份的数据,我也看到线路已连接。我想避免在图表上绘制那些缺失的月份。另外,我想为春季(3 月、4 月、5 月)画一个蓝色阴影,表示春季。

library(tidyverse)
library(lubridate)

DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "day"),
                  Obs = runif(1826,1,5), Sim = runif(1826,1,5)) %>% 
   separate(Date, into = c("Year", "Month", "Day")) %>% 
  filter(between(Month, 3,10)) %>% 
  mutate(Date = make_date(Year, Month, Day))

ggplot(data = DF, aes(x = Date))+
  geom_line(aes(y = Sim, col = "red"))+
  geom_line(aes(y = Obs, col = "blue"))

所需的输出:我正在寻找如下图,其中春季以蓝色阴影突出显示。

【问题讨论】:

    标签: r dataframe ggplot2 tidyverse lubridate


    【解决方案1】:

    试试这个方法:

    library(tidyverse)
    library(lubridate)
    #Data
    DF <- data.frame(Date = seq(as.Date("2001-01-01"), to = as.Date("2005-12-31"), by = "day"),
                     Obs = runif(1826,1,5), Sim = runif(1826,1,5)) %>% 
      separate(Date, into = c("Year", "Month", "Day")) %>% 
      filter(between(Month, 3,10)) %>% 
      mutate(Date = make_date(Year, Month, Day))
    #Create springs var
    DF <- DF %>% mutate(Spring=ifelse(Month %in% c('03','04','05'),'Spring',NA)) %>%
      filter(!Month %in% c('11','12'))
    #Plot
    ggplot(data = DF, aes(x = Date,group=Year))+
      geom_line(aes(y = Sim, col = "red"))+
      geom_line(aes(y = Obs, col = "blue"))+
      geom_bar(stat = 'identity',aes(x=Date,y=5,fill=Spring),alpha=0.25)+
      scale_color_manual(values=c('red','blue'),
                         labels=c('Sim','Obs'))+
      scale_alpha_manual(values=c(0.5,0.5))+
      scale_fill_manual(values=c('blue','pink'),
                        limits='Spring')+
      scale_y_continuous(limits = c(NA,5),expand = c(0,0))+
      scale_x_date(breaks = as.Date(paste0(unique(format(DF$Date,'%Y-%m')),'-01')),
                   date_labels = '%Y-%m',expand = c(0.05,0))+
      theme_bw()+labs(color='',fill='')+
      theme(axis.text.x = element_text(angle=90),
            strip.background = element_blank(),
            strip.text = element_blank(),
            panel.spacing = unit(-0.5, "lines"),
            panel.border = element_blank())+
      facet_wrap(.~Year,scales = 'free_x',nrow = 1)
    

    输出:

    【讨论】:

    • 谢谢鸭子,有没有办法完全避免在缺少的月​​份中出现这些空白? IE。绘制第 3 个月到第 10 个月的数据,但缺失月份没有间隔。
    • 我还看到阴影条具有 y 比例(y = 5)。它可以以我们不需要指定y值的方式定义吗?你可以看到它在顶部留下了空白。取决于数据范围是什么,它会做同样的事情
    • @Hydro 添加了一个更新,由于您的日期变量,这是您可以减少的最大空间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-20
    • 2016-01-30
    • 2018-08-22
    • 1970-01-01
    相关资源
    最近更新 更多