ggplot2: scale_*_time 格式不正确

ggplot2: scale_*_time formats incorrectly

目标

使用ggplot2::scale_*_time以特定方式格式化时间轴(使用最新版本ggplot2)。

最小 Reprex

# Example data
tib1 <- tibble::tibble(
    x = 1:10,
    y = lubridate::as.duration(seq(60, 600, length.out = 10))
)

使用 ggplot2::scale_*_timeformat = "%R" 不起作用 - 坐标轴使用 %H:%M:%S:

格式化
# This doesn't work
ggplot2::ggplot(tib1) +
    ggplot2::geom_point(ggplot2::aes(x,y)) +
    ggplot2::scale_y_time(labels = scales::date_format(format = "%R"))

但是,我可以将时间变量 (y) 添加到任意日期,然后格式化结果 datetime 对象:

# This works
tib2 <- tib1 %>%
    dplyr::mutate(z = lubridate::ymd_hms("2000-01-01 00:00:00") + y)

ggplot2::ggplot(tib2) +
    ggplot2::geom_point(ggplot2::aes(x,z)) +
    ggplot2::scale_y_datetime(labels = scales::date_format(format = "%R"))

显然,我不希望在我的时间中添加任意日期以使轴格式正确(在引入 ggplot2::scale_*_time 之前我必须这样做,但希望现在避免)。

您的持续时间会自动转换为 hms 对象,始终显示为 hh:mm:ss(即 hms)。 scales::date_format 使用 format ,它不对 hms 对象做任何事情,只是将它们转换为字符向量。理想情况下,很容易有一个适当的 format.hms 方法来控制显示多少,但就目前而言 hms:::format.hms 实际上并没有接受任何 format 参数。

一个解决方案是简单地删除前三个字符:

ggplot2::ggplot(tib1) +
  ggplot2::geom_point(ggplot2::aes(x,y)) +
  ggplot2::scale_y_time(labels = function(x) substring(x, 4))