How to format the x-axis of the hard coded plotting function of SPEI package in R?

前端 未结 1 623
醉话见心
醉话见心 2020-12-19 19:26

I am using the SPEI package along with its sample monthly data of 32 years. I want to modify the x-axis labels to reflect the years not the numbers. However, the hard coded

相关标签:
1条回答
  • 2020-12-19 19:32

    I did not quite understand the plot.spei function, so I used ggplot2.

    Basically I built a data frame with ts of the fitted values and created a color/fill condition for positive (pos) or negative (neg) values.

    library(zoo)
    library(tidyverse)
    DF <- zoo::fortify.zoo(SPEI_12$fitted)
    DF <- DF %>% 
      dplyr::select(-Index) %>% 
      dplyr::mutate(Period = zoo::as.yearmon(paste(wichita$YEAR, wichita$MONTH), "%Y %m")) %>% 
      na.omit() %>% 
      dplyr::mutate(sign = ifelse(ET0_har >= 0, "pos", "neg"))
    
    ggplot2::ggplot(DF) +
      geom_bar(aes(x = Period, y = ET0_har, col = sign, fill = sign),
                show.legend = F, stat = "identity") +
      scale_color_manual(values = c("pos" = "darkblue", "neg" = "red")) +
      scale_fill_manual(values = c("pos"  = "darkblue", "neg" = "red")) +
      scale_y_continuous(limits = c(-3, 3), 
                         breaks = -3:3) +
      ylab("SPEI") + ggtitle("12-Month SPEI") +
      theme_bw() + theme(plot.title = element_text(hjust = 0.5))
    


    Edit: An additional idea.

    DF2 <- DF %>% 
      tidyr::spread(sign, ET0_har) %>% 
      replace(is.na(.), 0)
    
    ggplot2::ggplot(DF2) + 
      geom_area(aes(x = Period, y = pos), fill = "blue", col = "black") +
      geom_area(aes(x = Period, y = neg), fill = "red",  col = "black") +
      scale_y_continuous(limits = c(-3, 3), 
                         breaks = -3:3) +
      ylab("SPEI") + ggtitle("12-Month SPEI") +
      theme_bw() + theme(plot.title = element_text(hjust = 0.5))
    

    0 讨论(0)
提交回复
热议问题