0

Reversing the date order is currently yet not supported in ggplot2, as stated in this GitHub issue. A reverse datetime scale could be created by manually defining a trans function from this answer.

Would be possible to manually define the 1. breaks and 2. labels of datetime axis, just like using the date_breaks and date_labels argument in scale_x_date/scale_y_date function?

Reprex

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)

Created on 2021-06-22 by the reprex package (v2.0.0)

wkth
  • 107
  • 1
  • 9

1 Answers1

0

Breaks

Manually define a numeric vector in Date class. Add it to the breaks argument of scale_y_continuous function.

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

enter image description here

Labels

Create a lambda function that takes the Date input and format the time. Add it to the labels argument of the scale_y_continuous function.

  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")
  )

enter image description here

wkth
  • 107
  • 1
  • 9