【发布时间】:2017-07-28 07:25:19
【问题描述】:
目标
使用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 之前我必须这样做,但希望现在避免)。
【问题讨论】: