【问题标题】:Reverse datetime axis with custom breaks in ggplot2在ggplot2中使用自定义中断反转日期时间轴
【发布时间】:2021-06-21 18:14:24
【问题描述】:

ggplot2 目前尚不支持反转日期顺序,如this GitHub issue 所述。可以通过手动定义 this answer 中的 trans 函数来创建反向日期时间刻度。

是否可以手动定义日期时间轴的 1.breaks 和 2.labels,就像在 scale_x_date/scale_y_date 函数中使用 date_breaks 和 date_labels 参数一样?

代表

library(ggplot2)
library(scales)

sample_data = data.frame(
  report_date = seq(as.Date("2021-01-01"), as.Date("2021-12-31"), by = "day"),
  report_var = seq(1, 365)
)

c_trans <- function(a, b, breaks = b$breaks, format = b$format) {
  a <- as.trans(a)
  b <- as.trans(b)

  name <- paste(a$name, b$name, sep = "-")

  trans <- function(x) a$trans(b$trans(x))
  inv <- function(x) b$inverse(a$inverse(x))

  trans_new(name, trans, inverse = inv, breaks = breaks, format = format)

}

rev_date <- c_trans("reverse", "date")


ggplot(sample_data, aes(x = report_var, y = report_date)) +
  geom_point() +
  scale_y_continuous(trans = rev_date)

由reprex package (v2.0.0) 于 2021-06-22 创建

【问题讨论】:

    标签: r ggplot2


    【解决方案1】:

    休息

    在 Date 类中手动定义一个数值向量。将其添加到scale_y_continuous 函数的breaks 参数中。

    scale_y_continuous(
      trans = rev_date,
      breaks = seq.Date(as.Date("2021-01-01"), as.Date("2021-12-31"), by = "2 weeks")
    )
    

    标签

    创建一个接受日期输入并格式化时间的 lambda 函数。将其添加到scale_y_continuous 函数的labels 参数中。

      scale_y_continuous(
        trans = rev_date,
        breaks = seq.Date(as.Date("2021-01-01"), as.Date("2021-12-31"), by = "2 weeks"),
        labels = ~ strftime(., "%b %d")
      )
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多