【问题标题】:How to format the x-axis of the hard coded plotting function of SPEI package in R?如何在R中格式化SPEI包的硬编码绘图功能的x轴?
【发布时间】:2019-09-21 11:17:51
【问题描述】:

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

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)

任何帮助将不胜感激。我想生成一个类似附件的图表。

【问题讨论】:

标签: r ggplot2 plot axis axis-labels


【解决方案1】:

我不太了解plot.spei的功能,所以我用了ggplot2

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

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

【讨论】:

  • 谢谢@bbiasi,这样就可以了。是的,plot.spei 函数是硬编码的,无法提供所需更改的灵活性。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-10-15
  • 1970-01-01
  • 2016-12-14
  • 2014-03-19
  • 2019-06-22
  • 1970-01-01
相关资源
最近更新 更多