r - ggplot 的时间轴

标签 r ggplot2

我有一个时间序列(每小时)数据,我想打印该数据的选定时间段。假设我想打印从 2019 年 1 月 1 日 00:00 到 2019 年 1 月 8 日 00:00 的一周数据。我希望刻度线从 2019 年 1 月 1 日的 00:00 开始。但出于我不知道的原因,ggplot 从 03:00 开始。我错过了什么吗?

这里是复制问题的示例代码:

library(ggplot2)
library(scales)
Sys.setenv( TZ = "GMT" )

datetime <- seq(from = as.POSIXct("2019-01-01", tz = "GMT"), length.out = 744, by = "hours")
random<- rnorm(744,100,20)

df <- data.frame(datetime,random)

time.start=as.POSIXct("2019-01-01 00:00",format="%Y-%m-%d %H:%M")
time.end=as.POSIXct("2019-01-08 00:00",format="%Y-%m-%d %H:%M")

png(filename = "test_ggplot.png", width = 800, height = 600, units = "px", pointsize = 24 )
plot.random = ggplot() + 
 geom_line(data=df, aes(x=datetime, y=random)) + 
 scale_x_datetime(limits = c(time.start,time.end),
          breaks = date_breaks("12 hours"),
          labels = date_format("%H:%M\n%d-%b")
          )
plot.random

这是图表,显示 x 轴刻度标记标签从 03:00 而不是 00:00 开始。

example ggplot time axis problem

最佳答案

我希望您的限制输入有效,这可能是一个错误。如果我删除 limits 参数并添加 expand 它似乎会做你想做的事:

ggplot() +
  geom_line(data = df %>% head(300), aes(x = datetime, y = random)) +
  scale_x_datetime(
    #limits = c(time.start, time.end),
    breaks = date_breaks("12 hours"),
    labels = date_format("%H:%M %d-%b"),
    expand = expand_scale(0)
  ) +
  theme(axis.text = element_text(angle = 90))

enter image description here

关于r - ggplot 的时间轴,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56042086/

相关文章:

r - 计算数据框中 TRUE 的列数

r - 为什么 metaMDS() 会产生水平分布的数据?

html - 在 div 上叠加图像

r - 我可以放大一个图并让其他图也以同样的方式缩放吗? (ggplot 和plotly)

r - 多边形可以很好地裁剪不同缩放级别的ggplot2/ggmap

r - 在R中使用脱字符训练后,如何计算ROC和ROC下的ROC?

r - 在R中使用dplyr查找每组的最大值

r - 使用 geom_smooth 添加回归线以在 R 中使用离散 x 轴绘制

r - ggplot2 中的 map 可视化/显示错误?

r - ggplot2中同一图上多个数据集的geom_point()和geom_line()