ggplot2:缩放_ * _时间格式错误

时间:2017-07-28 07:25:19

标签: r ggplot2 lubridate

目标

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

最小代表

# 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之前我必须这样做,但现在希望避免)。

1 个答案:

答案 0 :(得分:4)

您的持续时间会以静默方式转换为hms个对象,该对象始终显示为hh:mm:ss(即hms)。 scales::date_format使用formathms个对象不做任何事情,而不是将它们转换为字符向量。理想情况下,使用适当的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))