使用 geom_rect 和 geom_histogram

Using geom_rect with geom_histogram

我想为使用 ggplot2 生成的直方图的背景着色。我想要背景 look like the one in the answer here.

这是我的代码:

dates <- seq(from = as.Date("2015/1/1"), to = as.Date("2015/12/31"), "day")

library(lubridate)
day <- yday(dates)
month <- month(dates)

df <- data.frame(day, month)

library(dplyr)
df %>%
sample_n(50) ->
df

library(ggplot2)
ggplot(df, aes(day)) + geom_histogram() + 
    scale_x_continuous(breaks = seq(0, 365, 10), limits = c(0, 365)) + 
    theme_bw()

产生这个情节的是:

这是我试过的方法,但没有用:

ggplot(df, aes(day)) + geom_histogram() + 
    geom_rect(xmin = day, xmax = day, ymin = -Inf, ymax = Inf, fill = month) + 
    scale_x_continuous(breaks = seq(0, 365, 10), limits = c(0, 365)) + 
    theme_bw()

您尝试从采样数据中绘制矩形,但这行不通,因为缺少数据。要绘制矩形,您需要指定每个月的开始和结束日期,为此最好创建一个额外的数据集。

这个数据框,我创建如下:

library(dplyr)
month_df <- df %>%
            group_by(month) %>%
            summarize(start=min(day),end=max(day) + 1) %>%
            mutate(month=as.factor(month))
# correct the last day of the year
month_df[12,"end"] <- month_df[12,"end"] - 1

用 50 个样本替换 df 之前,执行此操作很重要。最后一行有点令人不快:为了避免矩形之间出现间隙,我在该月的最后一天添加了一个。这不应该在最后一天完成。它有效,但也许您会找到更简洁的解决方案...

month_df的前几行应该是

   month start end
1      1     1  32
2      2    32  60
3      3    60  91

现在,情节可以由

创建
ggplot(df) + 
  geom_rect(data=month_df,aes(xmin = start, xmax = end, fill = month),
            ymin = -Inf, ymax = Inf) + 
  geom_histogram(aes(day)) + 
  scale_x_continuous(breaks = seq(0, 365, 10), limits = c(0, 365)) + 
  theme_bw()

几点说明: * geom_rect()geom_histogram() 之前很重要,以便在背景中显示矩形。 * 我从 ggplot() 中删除了 aes(day) 并放入 geom_histogram() 中,因为它只在那里使用。否则,它会混淆 geom_rect(),你会得到一个错误。 * ymin=-Infymax=Inf 不是数据的美学映射,因为它们实际上被设置为常量。所以没有必要把这些放在aes()里面。不过,如果你把它们放在里面 aes(),就不会发生什么坏事。

我得到的情节如下: