【问题标题】:How do I scale an axis for time intervals using ggplot2?如何使用 ggplot2 缩放时间间隔的轴?
【发布时间】:2015-12-18 18:39:40
【问题描述】:

假设我想绘制一堆时间间隔的直方图:

library(ggplot2)
library(dplyr)

# Generate 1000 random time difftime values
set.seed(919)
center <- as.POSIXct(as.Date("2014-12-18"))
df <- data.frame(
    center, 
    noise = center + rnorm(1000, mean = 86400, sd = 86400 * 3)
    ) %>%
  mutate(diff = center - noise)

# Plot histogram of the difftime values -- 
# coerce to numeric, because otherwise it won't plot
qplot(data = df, x = as.numeric(diff), geom = "histogram")

我明白了这个情节:

有没有办法将 x 轴更改为合理的日期时间值? (也就是说,我希望将 86400 标记为“1 天”,将 -86400 标记为“- 1 天”等)我可以通过设置休息时间和标签来手动执行此操作,但我希望ggplot 有一种方法可以自动处理 difftime 值。

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    您可以使用difftime()days 作为单位,而不是减去日期。

    library(ggplot2)
    library(dplyr)
    
    # Generate 1000 random time difftime values
    set.seed(919)
    center <- as.POSIXct(as.Date("2014-12-18"))
    df <- data.frame(
        center, 
        noise = center + rnorm(1000, mean = 86400, sd = 86400 * 3)
        ) %>%
      mutate(diff = difftime(center, noise, unit = "days"))
    
    # Plot histogram of the difftime values -- 
    # coerce to numeric, because otherwise it won't plot
    qplot(data = df, x = as.numeric(diff), geom = "histogram") +
      xlab("Days") + ylab("Count")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-07-06
      相关资源
      最近更新 更多