【问题标题】:ggplot2: scale_*_time formats incorrectlyggplot2: scale_*_time 格式不正确
【发布时间】: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_*_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 之前我必须这样做,但希望现在避免)。

【问题讨论】:

    标签: r ggplot2 lubridate


    【解决方案1】:

    您的持续时间会静默转换为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))
    

    【讨论】:

      猜你喜欢
      • 2019-01-29
      • 2015-08-29
      • 2012-02-15
      • 2019-04-29
      • 2011-08-26
      • 1970-01-01
      • 2013-03-20
      • 2018-01-21
      • 2016-07-19
      相关资源
      最近更新 更多