【问题标题】:Using geom_rect with geom_histogram将 geom_rect 与 geom_histogram 一起使用
【发布时间】:2015-07-20 09:05:55
【问题描述】:

我想为使用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()

【问题讨论】:

  • 答案很清楚你需要做什么。哪一部分难以理解?
  • 您是否查看过您的问题的其他答案? stackoverflow.com/questions/31510796/…
  • @RomanLuštrik 如果您查看链接答案中的rectsgeom_rectxstartxend 参数每个都有自己的变量。但是在我创建的df 中,我只有一个变量day,它被geom_histogram 转换为bin,所以不清楚xminxmax 的值应该是什么。
  • 背景的着色在第二层完成,可以(或不)连接到使用的原始数据集。你告诉 ggplot 是你想在 x 轴上每天绘制一些东西,在 y 轴上从 -Inf 到 Inf 绘制一些东西。如果您考虑一下,每天的区域宽度为 0。传递给 xmin 和 xmax 的值必须使它们产生正差。

标签: r ggplot2 data-visualization


【解决方案1】:

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

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

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

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

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() 中,就不会发生任何不好的事情。

我得到的情节如下:

【讨论】:

    猜你喜欢
    • 2017-07-19
    • 2021-10-01
    • 2014-05-29
    • 1970-01-01
    • 2018-06-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多