说我想绘制一堆时间间隔的直方图:
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标记为&#34; 1天&#34;, - 86400标记为&#34; - 1天&#34;等)我可以手动执行此操作通过设置中断和标签,但我希望ggplot能够自动处理difftime值。
答案 0 :(得分:3)
您可以使用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")