在每个方面将轴日期扩展到完整的一个月

Expand axis dates to a full month in each facet

我正在绘制路由器统计信息(从 merlin speed monitoring tool 收集)。

图表按年月分面,我希望每个月的 x 轴扩展到整个月,即使我只有一个月的部分数据。

在下面的示例中,2022 年 1 月的数据不完整(仅 6 小时或 所以数据)。

我试过的代码:

library(tidyverse)
library(scales)
X.df <- read.csv(url("https://pastebin.com/raw/sGAzEDe6")) %>%
   mutate(date = as.POSIXct(date, origin="1970-01-01")) 

ggplot(X.df , aes(date, Download, colour = Download)) +
  geom_line()+
facet_wrap(~ month,  scale="free_x",  ncol = 1) +
    scale_colour_gradient(low="red",high="green", limits=c(0.0, 50), oob = squish) +
  scale_x_datetime(date_labels = "%d/%m", breaks = "7 day", minor_breaks = "1 day") +
  coord_cartesian(ylim = c(0, 60))

同样,我希望每个方面的 x 轴范围涵盖整个月。因此,我希望 2021-12 方面的 X 轴从 2021 年 12 月 1 日到 2021 年 12 月 31 日 运行,2022-01 方面的 X 轴从 2022 年 1 月 1 日到 31 日 运行 2022 年 1 月。

有没有办法在 ggplot2 中强制执行此操作?

一个额外的、较小的独立示例来尝试您的代码:

X.df <- tribble(
  ~date, ~month, ~Download,
"2021-12-01T00:30:36Z","2021-12",20.13,
"2021-12-07T06:30:31Z","2021-12",38.95,
"2021-12-14T08:00:31Z","2021-12",38.44,
"2021-12-21T09:30:29Z","2021-12",28.57,
"2021-12-28T16:00:31Z","2021-12",30.78,
"2021-12-31T13:00:28Z","2021-12",55.45,
"2022-01-01T00:00:28Z","2022-1",55.44,
"2022-01-01T02:30:29Z","2022-1",55.63,
"2022-01-01T03:00:29Z","2022-1",55.75,
"2022-01-01T05:00:29Z","2022-1",55.8,
"2022-01-07T03:00:29Z","2022-1",53.6,
"2022-01-07T05:00:29Z","2022-1",51.8
)

一如既往,提前致谢。皮特

更新 II:删除了以前的版本:

  1. 在您的数据库中只有一个 2022 年 1 月的日期
  2. 在数据框中,我们使用 tidyr 包中的 complete 完成 2022 年 1 月的日期。
library(tidyverse)
library(lubridate)
X.df %>% 
  mutate(date = ymd(date)) %>% 
  group_by(month(date)) %>% 
  complete(date = seq(min(date), max(ceiling_date(date, unit = "month") - ddays(1)), by = 'day')) %>%
  fill(month) %>% 
  ggplot(aes(x = date, Download, colour = Download)) +
  geom_line()+
  facet_wrap(~ month,  scale="free_x",  ncol = 1) +
  scale_colour_gradient(low="red",high="green", limits=c(0.0, 50), oob = squish) +
  scale_x_date(date_breaks = "1 day", date_labels =  "%d/%m", expand = c(0, 0)) +
  coord_cartesian(ylim = c(0, 60))