2017-07-28 60 views
3

目标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_*_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被引入,但现在希望避免)。

回答

3

您的持续时间会悄无声息地转换为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))