使用 ggplot2 创建甘特图:scale_x_date 函数可以将日期显示为季度(例如 2020 年第四季度)吗?

Creating Gantt charts with ggplot2: can the scale_x_date function display dates as quarters (eg Q4 2020)?

我正在使用 ggplot2 准备甘特图。我找到了一个最有用的方法,但我想进一步提高我的输出。

以下示例代码创建了一个数据框(这样设置是因为动态编辑相对容易):

df <- as.data.frame(rbind(
    c("Category_1", "task_1", '2020-10-01', '2020-12-31'),
    c("Category_1", "task_2", '2021-01-01', '2021-04-01'),
    c("Category_2", "task_3", '2021-06-15', '2021-10-01'))) %>%
  select("Category" = 1, "task" = 2, "start" = 3, "end" = 4) %>%
  mutate(Category = (factor(Category, levels = (unique(Category)))),
         task = fct_rev(factor(task, levels = (task))),
         start = as.Date(start), 
         end = as.Date(end)) %>%
  mutate(lab_pos = start) %>%
  pivot_longer(3:4, names_to = "variable", values_to = "value")

然后这段代码创建了甘特图(为分享而简化):

ggplot(df, aes(value, task, color = Category)) + 
  geom_line(size = 14, show.legend = FALSE) +
  scale_x_date(date_labels = " %y %b", 
               limits = c(as.Date('2020-06-30'), as.Date('2021-12-31')), 
               date_breaks = '3 months', date_minor_breaks = "1 month", 
               position = "top") +
  labs(x = NULLy = NULL) +
  facet_grid(Category ~ ., space = "free_y", scales = "free_y", switch = "both")  

所以问题是 我怎样才能以季度而不是日期显示由 scale_x_date 生成的 x 轴单位? 例如,我不是 1 月 21 日,而是更喜欢 Q1 21。与 scale_x_date 相比,是否有更好的方法?

第二个问题是:如果我能得到四分之一的标签,我能不能把那个标签移到四分之一的中间,这样主要的网格线就和四分之一相邻,标签就在它们之间,标识整个区域作为季度?

我们可以使用 labels 参数代替 date_labels 并传递自定义函数以从日期中提取季度信息。

library(ggplot2)

ggplot(df, aes(value, task, color = Category)) + 
  geom_line(size = 14, show.legend = FALSE) +
  scale_x_date(labels =  function(x) paste(quarters(x), format(x, '%Y')),
               limits = c(as.Date('2020-06-30'), as.Date('2021-12-31')), 
               date_breaks = '3 months', date_minor_breaks = "1 month", 
               position = "top") +
  labs(x = NULL,y = NULL) +
  facet_grid(Category ~ ., space = "free_y", scales = "free_y", switch = "both")