简体   繁体   English

如何使用ggplot2在时间间隔上缩放轴?

[英]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.

相关问题 如何使用ggplot2在Y轴上设置时间范围(HH:MM:SS)? - How do I set time range (HH:MM:SS) on Y-axis using ggplot2? 如何在r的ggplot2中缩放x轴的时间(小时)? - How can I scale the time (hours) of my x-axis in ggplot2 in r? ggplot2轴:设置间隔,对数刻度和指数,而不是科学的 - ggplot2 axis: set intervals, logarithmic scale, and exponents instead of scientific ggplot2 轴刻度总是以科学数字出现。 我该如何改变它 - ggplot2 axis scale always comes out in scientific numbers. How do I change it 如何使用ggplot2在y轴上缩放因子 - how to scale factors in y-axis using ggplot2 如何使用 ggplot2 在此 plot 中获取轴刻度和刻度? - How to get axis scale and ticks in this plot using ggplot2? 使用对数刻度时,如何在ggplot2中设置轴范围? - How can I set axis ranges in ggplot2 when using a log scale? 使用R中的ggplot2进行时序图时,如何在x轴上正确缩放日期? - How do I scale dates correctly on x-axys when doing time-series graph using ggplot2 in R? 如何使用 R 中的 ggplot2 在轴刻度标记上添加轴标签,类似于 Fivethirtye8 样式? - How do I add an axis label on an axis tick mark using ggplot2 in R, similar to the fivethirtyeight style? ggplot2:y 轴上有两个变量(以相同比例测量)的散点图:如何更改美学并添加单独的回归线? - ggplot2: scatterplot with two variables (measured on the same scale) on the y-axis: how do I change the aesthetics & add seperate regression lines?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM