[英]How do I scale an axis for time intervals using ggplot2?
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: 我得到这个情节:
Is there a way to change the x-axis to be reasonable date-time values? 有没有办法将x轴更改为合理的日期时间值? (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.
(也就是说,我希望将86400标记为“ 1天”,将-86400标记为“-1天”,等等。)我可以通过设置中断和标签来手动执行此操作,但我希望ggplot有一种自动处理difftime值的方法。
Instead of subtracting the dates you can use difftime()
and use days
as the units. 不用减去日期,可以使用
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")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.