如何创建每月对齐的直方图?

问题描述 投票:0回答:1

当使用 ggplot 的 geom_histogram() 创建包含每个月的 bin 的直方图时,这些 bin 似乎没有与正确的日历月份对齐,也没有所需的高度。

我已经搜索了一段时间,但仍然没有找到令人满意的解决方案来绘制每月数据的直方图,其中标签和垃圾箱准确地反映了日历月份。我有 2 个目标,并且主要尝试了第一个目标,但也请求第二个目标的帮助。

目标1:[高效]使用ggplot为每个日历月制作一个带有bin的直方图,并清楚地标记每个bin的月份

目标 2:[高效]使用 ggplot 为每个日历月制作一个带有 bin 的直方图,并且只明确标记日历季度(例如,10 月 1 日 - 12 月 31 日是“2022 年第 4 季度”)

下面我展示了一个示例,在 2022 年 11 月 15 日至 2023 年 12 月 31 日期间有 400 个观测值。通过设置种子,我们可以重复地确定 2022 年 11 月有 16 个观测值。我的代码显示了 2 个正在尝试的绘图示例使用 binwidth 和 scale_x_date(date_breaks),既不会生成标签与相应 bin 精确对齐的图,也不会生成第一个 bin 的 y 值为 16 的图。

library(ggplot2)
set.seed(123)

# Create a dataframe with 400 random dates between Nov 15 2022 and Dec 31 2023
start_date <- as.Date("2022-11-15")
end_date <- as.Date("2023-12-31")
random_dates <- sample(seq(start_date, end_date, by="days"), 400, replace=TRUE)
df <- data.frame(Date = random_dates)

# There are 16 observations in November 2022
sum(random_dates >= as.Date("2022-11-01") & random_dates <= as.Date("2022-11-30"))

# Using binwidth = 30
ggplot(df, aes(x = Date)) +
  geom_histogram(binwidth = 30, fill = "lightgrey", color = "black") +
  labs(title = "binwidth = 30 (Nov 15 2022 - Dec 31 2023)",
       x = "Date",
       y = "Count") +
  theme_minimal()

# Using date_breaks = '1 month' (and warning says that it defaults to bins = 30)
ggplot(df, aes(x = Date)) +
  geom_histogram(fill = "lightgrey", color = "black") +
  scale_x_date(date_breaks = "1 month", date_labels = "%b %Y") +
  labs(title = "date_breaks = '1 month' (Nov 15 2022 - Dec 31 2023)",
       x = "Date",
       y = "Count") +
  theme_minimal() +
  theme(axis.text.x = element_text(angle = 90, hjust = 1))

这些是生成的图:

Histogram using binwidth = 30 argument

Histogram using scale_x_date(date_breaks =

提前谢谢您

r date ggplot2 plot histogram
1个回答
0
投票

最巧妙的方法可能是事先总结您的数据。使用

lubridate::floor_date
查找月份,然后汇总为
count
每个月的数字。然后,您可以将月份列转换为格式良好的字符向量,最后将其作为一个因素,以便顺序正确。那么剧情就非常简单了
geom_col
:

library(tidyverse)

df %>%
  mutate(month = lubridate::floor_date(Date, 'month')) %>%
  count(month) %>%
  mutate(month = fct_inorder(as.character(month, format = '%b %Y'))) %>%
  ggplot(aes(month, n)) +
  geom_col(width = 1, color = 'black', fill = 'gray') +
  theme(axis.text.x = element_text(angle = 90, vjust = 0.5))

© www.soinside.com 2019 - 2024. All rights reserved.