2
votes

Say I want to plot a histogram of a bunch of time intervals:

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")

I get this plot:

histogram

Is there a way to change the x-axis to be reasonable date-time values? (That is, I'd want 86400 to be labelled as "1 day", -86400 to be labelled as "- 1 day", etc.) I could do this manually by setting breaks and labels, but I'm hoping that ggplot has a way to handle difftime values automatically.

1

1 Answers

3
votes

Instead of subtracting the dates you can use difftime() and use days as the units.

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")

enter image description here