目标
使用ggplot2::scale_*_time
以特定方式格式化时间轴(使用最新版本的ggplot2
)。
最小代表
# Example data
tib1 <- tibble::tibble(
x = 1:10,
y = lubridate::as.duration(seq(60, 600, length.out = 10))
)
将ggplot2::scale_*_time
与format = "%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
之前我必须这样做,但现在希望避免)。
答案 0 :(得分:4)
您的持续时间会以静默方式转换为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))