在 r 中绘制每连续 n 年的直方图

plot histogram of every consecutive n years in r

我有几年的每日降雨量数据,例如:

date         value
01/01/1990    1.02
02/01/1990    0.50
03/01/1990    0.00
.........     ...
.........     ...
12/12/2015    10.25

我需要从中绘制连续五年的直方图。即,1990 年至 1995 年的直方图,然后是 1991 年至 1996 年等等。我尝试使用 ggplot 和 facet,找不到方法。

rf_facet <- inp %>%
  filter(between(rain,1,100))

ggplot(rf_facet, aes(x = rain)) + facet_wrap(~year, nrow = 5) +
  geom_histogram(aes(fill =..count..))

这个只能出一年的剧情,我是连续五年找

如有任何帮助,我们将不胜感激。 示例数据是 here

这是一个使用 ggplot2cowplot 的示例。我有一个从 i 年到 i+5 年绘制的函数。我 运行 在所有可能的连续 5 年期间使用 lapply

# Dummy data
df <- data.frame(date = seq(as.Date('01/01/1990', format = "%d/%m/%Y"), 
                      as.Date('31/12/2000', , format = "%d/%m/%Y"), by="day"))
df$value <- runif(nrow(df), 0, 100)

# Load libraries
library(dplyr)
library(cowplot)
library(ggplot2)
library(lubridate)

# Plotting function
plot_rain <- function(i){
  g <- ggplot(df %>% filter(between(year(date), i, i+5)))
  g <- g + geom_histogram(aes(value))
  g <- g + xlab("Rainfall (mm)") + ylab("# of obs")
  g <- g + ggtitle(paste(i, i+5, sep = "-"))
}

# Run for all years
plist <- lapply(min(year(df$date)):(max(year(df$date))-5), plot_rain)

# USe cowplot to plot the list of figure
plot_grid(plotlist = plist, ncol = 2)
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

reprex package (v0.2.1)

于 2019-03-07 创建