GGPLOT2:错误
问题描述:
使用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_*_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
被引入,但现在希望避免)。
答
您的持续时间会悄无声息地转换为hms
对象,它始终显示为hh:mm:ss
(即hms
)。 scales::date_format
使用format
它不会对hms
对象做任何事情,除了将它们转换为字符向量。理想情况下,拥有适当的format.hms
方法可以很容易地控制显示的数量,但因为它实际上并没有采取任何format
参数hms:::format.hms
。
一种解决方案是简单地删除的前三个字符:
ggplot2::ggplot(tib1) +
ggplot2::geom_point(ggplot2::aes(x,y)) +
ggplot2::scale_y_time(labels = function(x) substring(x, 4))