【问题标题】:Expand axis dates to a full month in each facet在每个方面将轴日期扩展到整月
【发布时间】:2022-01-01 11:38:36
【问题描述】:

我正在绘制路由器统计信息(从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 日到 2022 年 1 月 31 日运行。

有没有办法在 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
)

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

【问题讨论】:

  • 如果我理解这个问题,请删除scale="free_x"?
  • 另外,使用date_breaks,而不是breaks
  • 嗨@PJP!请让您的问题自成一体,即在实际问题中创建易于复制粘贴的最小数据,而不是依赖可能随时过时的链接。这将增加您的帖子对未来访问者的价值。每个“年月”的三个四个日期应该足以说明您的问题。还。所需的绘图输出可能很难用文字来描述,并且通常会导致徒劳的猜测,如下所示。因此,请随意添加显示所需结果的简单绘图。干杯
  • @PJP 很好,非常感谢!我做了一些小的修改 - 我希望你觉得它们没问题。干杯
  • 关于我删除“EDIT”,请参考这篇文章:Should "Edit:" in edits be discouraged?;删除有问题的“答案”:When is it cool to summarize answers in question edit?

标签: r date ggplot2 axis


【解决方案1】:

更新 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))

【讨论】:

  • 请看我的更新!
  • @PJP 这应该是公认的答案。但我会用geom_point() + geom_smooth(method = 'gam', formula = y ~ s(x, bs = "cs")) 代替geom_line
  • @TarJae - 非常好 - 完成了这项工作。谢谢你。你能解释一下为什么 group_by 是必要的(我玩过你的代码,没有 group_by 就不行)。
  • group_by 指的是complete。没有group_by,2022 年全年都将完成。也许您应该在complete 之后添加ungroup()。 :-)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 2018-07-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多