如何在R中格式化SPEI软件包的硬编码绘图功能的x轴? [英] How to format the x-axis of the hard coded plotting function of SPEI package in R?

查看:173
本文介绍了如何在R中格式化SPEI软件包的硬编码绘图功能的x轴?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用SPEI软件包及其32年的每月样本数据.我想修改x轴标签以反映年份而不是数字.但是,硬编码绘图功能不允许我这样做.我疲于提取SPEI$fitted数据,并尝试使用ggplot复制相同的图,但是没有成功.这是示例代码

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.

推荐答案

我不太了解plot.spei函数,所以我使用了ggplot2.

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

基本上,我用ts的拟合值构建了一个数据框,并为正数创建了一个颜色/填充条件(pos)或负值(neg).

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

修改:一个附加提示.

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

这篇关于如何在R中格式化SPEI软件包的硬编码绘图功能的x轴?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆