R - 缺失数据的scale_x_date问题

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

我有这个数据样本:

sample <- data.frame(service_type = c("A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C","A","B","C"),
                     qty = c(38,185,87,29,12,133,2,14,31,2,9,59,60,43,137,135,31,159,15,32,1,25,60,100,30,40,50),
                     year_week = c("2023 - CW48","2023 - CW48","2023 - CW48","2023 - CW49","2023 - CW49","2023 - CW49","2023 - CW50","2023 - CW50","2023 - CW50","2023 - CW51","2023 - CW51","2023 - CW51","2023 - CW52","2023 - CW52","2023 - CW52","2024 - CW01","2024 - CW01","2024 - CW01","2024 - CW02","2024 - CW02","2024 - CW02",'2024 - CW03','2024 - CW03','2024 - CW03','2024 - CW04','2024 - CW04','2024 - CW04'),
                     xlabel2 = c("Nov-23","Nov-23","Nov-23","Dec-23","Dec-23","Dec-23","Dec-23","Dec-23","Dec-23","Dec-23","Dec-23","Dec-23","Dec-23","Dec-23","Dec-23","Jan-24","Jan-24","Jan-24","Jan-24","Jan-24","Jan-24","Jan-24","Jan-24","Jan-24","Jan-24","Jan-24","Jan-24")
)

sample <- sample %>%
  mutate(date = as.Date(paste0(year_week, 1), "%Y - CW%U%u")) 

如您所见,我错过了 CW53-2023 的数据,并且日期字段从 25/12/2023 跳转到 08/01/2024;当我绘制数据时,date_breaks 选项创建 2024-CW00 没有数据的一周。 请参阅下面的绘图代码和绘图本身。知道如何删除那一周吗?

ggplot(sample ) +
  
  aes(x = date, y = qty, fill = service_type) +
  
  geom_col(position = "dodge") +
  
  geom_line(aes(group = 1), stat = "summary", fun = sum, linetype = "dashed", size = 1, color = '#FF507B') +
  geom_point(aes(group = 1), stat = "summary", fun = sum, size = 2, color = '#FF507B') +
  
  geom_text(aes(label=qty), 
            position=position_dodge(7 * 0.9), vjust = 0)+
  
  geom_text(aes(label = after_stat(y), group = 1),
            stat = "summary", fun = sum, vjust = 0, size = 3) +
  
  scale_fill_manual(values = c(A = "#FFC000", B = "#92D050", C = "#AE5AFF"))+
  scale_x_date(
    date_labels = "%Y - CW%U",
    date_breaks = "1 week",
    sec.axis = dup_axis(
      breaks = as.Date(paste0("15-", unique(sample$xlabel2)), "%d-%b-%y"),
      labels = \(x) format(x, "%b-%y")
    )
  ) +
  theme_minimal() +
  theme(legend.position = "left",
        axis.text.x.bottom = element_text(angle=90, hjust=1, vjust = 0.5),
        axis.title = element_blank(), legend.title = element_blank(),
        panel.grid.minor.x = element_blank())

r ggplot2 scale
1个回答
0
投票

我们可以使用

ggbreak
。我将从
"2023-12-25"
中断到
"2024-01-08"

gg <- ggplot(...) # your code unmodified
gg +
  ggbreak::scale_x_break(breaks = as.Date(c("2023-12-25", "2024-01-08")))

这明显扭曲了 x 轴,所以我们可以稍微缓冲一下;不确定我们是否可以“完美”自动化此操作。

gg +
  ggbreak::scale_x_break(breaks = as.Date(c("2023-12-25", "2024-01-08")) + c(1.5, -1.5))

最大的“啊?”关于这一点是红色虚线被打破(清楚地理解为什么)并且两个存根似乎没有相交。

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