Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
944 views
in Technique[技术] by (71.8m points)

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

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 plotting function won't allow me to do this. I tired to extract the SPEI$fitted data and tried to replicate the same plot with ggplot but did not succeeded. Here is the sample code

install.packages("SPEI")
library(SPEI)
data("wichita")
wichita$PET=hargreaves(Tmin=wichita$TMIN, Tmax = wichita$TMAX, lat = 37.64)
wichita$BAL=wichita$PRCP - wichita$PET
SPEI_12=spei(wichita[,"BAL"],12)
plot.spei(SPEI_12, main = 12-Month SPEI)

Any help would be appreciated. I want to produce a graph like attached.enter image description here

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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))

enter image description here


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))

enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...