在 ggplot 中的 x 轴上显示工作日和时间

Show weekdays and times on the x-axis in ggplot

我有一个包含事件的数据集。这些事件有开始时间和持续时间。我想创建一个散点图,x 轴为开始时间,y 轴为持续时间,但我想更改 x 轴以使其显示一周的过程。也就是说,我希望 x 轴从星期一 00:00 和 运行 开始到星期日 23:59.

我在网上找到的所有解决方案都向我展示了如何在工作日进行分组求和,这不是我想要做的。我想单独绘制所有数据点,我只是想将日期轴减少到工作日和时间。

有什么建议吗?

这就是您所需要的。它所做的是通过将每个观察值放在一周内来创建一个新变量,然后以必要的格式生成散点图。

library(lubridate)
library(dplyr)

set.seed(1)
tmp <- data.frame(st_time = mdy("01-01-2018") + minutes(sample(1e5, size = 100))) 
tmp <- tmp %>% 
    mutate(st_week = floor_date(st_time, unit = 'week')) %>% # calculate the start of week
    mutate(st_time_inweek = st_time - st_week) %>% # calculate the time elapsed from the start of the week
    mutate(st_time_all_in_oneweek = st_week[1] + st_time_inweek) %>% # put every obs in one week
    mutate(duration = runif(100, 0, 100)) # generate a random duration variable

这是生成情节的方法。 "%a %H:%M:%S" 部分可能只是 "%a",因为时间部分没有提供信息。

library(ggplot2)
ggplot(tmp) + aes(x = st_time_all_in_oneweek, y = duration) +
    geom_point() + scale_x_datetime(date_labels = "%a %H:%M:%S", date_breaks = "1 day")

"%a" 情节如下所示: