【问题标题】:R - avoid to show milliseconds with lubridate hms and ggplotR - 避免使用 lubridate hms 和 ggplot 显示毫秒
【发布时间】:2018-06-22 07:55:43
【问题描述】:

我有不同的数据帧 (df),每个人都有这样的持续时间向量:

  Duration
  02:05:30
  01:00:58
  00:40:21
  00:54:26

我要做的是用 ggplot 以下列方式绘制这些持续时间:

    df$Duration <- lubridate::hms(df$Duration)

    p <- ggplot(df, aes(Duration)) + scale_x_time("Duration") + 
    stat_bin(aes(y =..count..), bins=30, fill = 'darkblue') + 
    scale_y_continuous(sec.axis = sec_axis(~./nrow(df), labels=percent))

这适用于 80% 的情况,但是,有时在图中,带有“持续时间”的 x 轴以“%H:%M:%S”格式显示时间,秒数有 6 个小数位(即 02:02:00.000000)这不是我想要的(我想要 02:02:00 代替)。我不知道它为什么这样做以及为什么它只对我拥有的一些数据帧这样做,我正在使用 lubridate::hms 因为它是处理持续时间大于24 小时(不是吗?),所以我不想在 POSIXct 中转换数据。 提前感谢您的帮助,我希望我已经足够清楚了!

【问题讨论】:

    标签: r ggplot2 lubridate


    【解决方案1】:

    如果您想将 X 轴标签设置为 2H 5M 30S 之类的东西,那么您可以尝试这种方法

    library(ggplot2)
    library(lubridate)
    
    df$Duration <- hms(df$Duration)
    
    ggplot(df, aes(period_to_seconds(Duration))) +     #converted duration to seconds for plotting
      stat_bin(aes(y = ..count..), bins = 30, fill = 'darkblue') + 
      scale_y_continuous(sec.axis = sec_axis(~./nrow(df), name = "percent")) +
      scale_x_continuous("Duration", labels = df$Duration, breaks = period_to_seconds(df$Duration)) +
      theme(axis.text.x = element_text(angle = 90, vjust = 0.5))
    

    哪些地块

    样本数据:

    df <- structure(list(Duration = c("02:05:30", "01:00:58", "00:40:21", 
    "00:54:26")), .Names = "Duration", class = "data.frame", row.names = c(NA, 
    -4L))
    

    【讨论】:

    • 谢谢,但我不想在 POSIXct 中转换数据,因为我必须处理超过 24 小时的持续时间,而 POSIXct 不支持。是否可以在 scale_x_time 中设置标签格式?
    • 如果有帮助别忘了let us know
    猜你喜欢
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多