【问题标题】:R ggplot date time major and minor axis breaks not aligningR ggplot日期时间长轴和短轴中断未对齐
【发布时间】:2021-02-17 01:02:33
【问题描述】:

我遇到了一个令我惊讶的是我以前从未遇到过并且我看不到任何答案的问题。我正在 ggplot 中绘制一些日期时间数据,并希望强制每日主要休息时间和季度每日次要休息时间(0、6、12、18)。当我设置 date_breaks = "1 day", date_minor_breaks = "6 hours" 时,日期休息时间是在午夜,但小休息时间取决于数据的开始时间,所以我有奇怪的偏移小休息时间。

我将为具有可变开始时间和结束时间(从 csvs 读取或根据特定条件从数据集过滤)的整个数据范围制作类似的图,因此我正在寻找一个通用的解决方案,它可以在没有固定开始时间。

为了更清楚,我在示例中将次要网格线设为蓝色,将主要网格线设为黑色

library(lubridate)
library(ggplot2)

testdat <- data.frame(DateTime = seq.POSIXt(from = ymd_hm("20210101 1200"), length.out = 130, by = "1 hour", tz = "UTC"),
                      y = rnorm(130))


ggplot(testdat, aes(x = DateTime, y = y))+geom_point()+
   scale_x_datetime(date_breaks = "1 day", date_minor_breaks = "6 hours", timezone  = "UTC",
                     date_labels = "%d %b %H:%M")+theme_bw()+
  theme(panel.grid.major.x =  element_line(colour = "black"),
        panel.grid.minor.x =  element_line(colour = "blue"))

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    一种方法是使用expand = c(0,0) 删除自动缩放填充,并指定两侧的小中断数为整数的限制:

    ggplot(testdat, aes(x = DateTime, y = y))+geom_point()+
      scale_x_datetime(date_breaks = "1 day", date_minor_breaks = "6 hours", timezone  = "UTC",
                       date_labels = "%d %b %H:%M", expand = c(0,0), 
                       limits = c(min(testdat$DateTime) - hours(6), 
                                  max(testdat$DateTime) + hours(6)))+
      theme_bw()+
      theme(panel.grid.major.x =  element_line(colour = "black"),
            panel.grid.minor.x =  element_line(colour = "blue"))
    

    【讨论】:

    • 我应该在问题中更清楚(我会编辑),但我将其应用于一大堆不同的数据集,数据在不同的时间开始和结束,所以我希望有所收获这不依赖于定义窗口。我想我可以找到开始前 6 小时的时间,但自动化听起来很痛苦
    • 很公平。问题是您不知道每个示例中的小中断有多大?在我的测试中,当我任意将第一个点更改为"20210101 1438" 时,这仍然可以正常工作。你能举个例子说明这行不通吗?
    • 哦,有趣。如果我将开始时间设置为"20210101 1438" 并使用您的代码,我仍然会遇到偏移中断。如果我的起点是 0:00、6:00、12:00 或 18:00,它只会修复结果
    • 据我所知,问题在于时区的处理。我有完全一样的问题。在 scale_x_datetime( ... , timezone="UTC") (或任何时区)中定义不同时区时,主要刻度/数据正在移位,但 date_minor_ticks="6 hours" 定义的次要刻度线似乎在不同的时区(可能是默认的 UTC)...到目前为止,我还没有找到将两者对齐的方法...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多