R ggplot2 - how to reverse y-axis having dates

153 Views Asked by At

In continuation with the ask from @David, I'm unable to reverse the y-axis having date field. I tried to reproduce the reprex - solution given by @Marcelo and @Oliver, but it is also throwing an error as below:

Error: Invalid input: time_trans works with objects of class POSIXct only

I have executed the same code as mentioned in the below link:

Reverse datetime (POSIXct data) axis in ggplot

Can somebody help to understand why we get this error? or is it because of any version issues in my system??

ggplot2 version 3.4.0 R version 4.2.2

I tried the same code as below:

MyData <-
  structure(list(Date = structure(c(1492979809.99827, 1492602845.68722, 
  1493093428.90318, 1492605578.0691, 1492961342.65056, 1492771976.83545, 
  1493020588.88485, 1493057018.85104, 1492852011.23873, 1492855996.55059
  ), class = c("POSIXct", "POSIXt")), Value = c(4.52885504579172, 
  6.0024610790424, 8.96430060034618, 7.06435370026156, 5.08460514713079, 
  3.47828012891114, 6.29844291834161, 0.898315710946918, 1.44857675535604, 
  5.74641009094194)), .Names = c("Date", "Value"), row.names = c(NA, 
  -10L), class = "data.frame")

library(ggplot2)
library(scales)

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

ggplot(MyData, aes(x=Value, y=Date)) +
  geom_point() + 
  scale_y_continuous(trans = rev_date)

Getting the error as below

Error: Invalid input: time_trans works with objects of class POSIXct only

1

There are 1 best solutions below

0
Allan Cameron On

I think creating a transformer is overkill here. You could simply make the date-time a numeric variable, and use as.POSIXct as a labelling function inside scale_y_reverse:

ggplot(MyData, aes(Value, as.numeric(Date))) +
  geom_point() + 
  scale_y_reverse("Date", labels = ~as.POSIXct(.x, origin = "1970-01-01"),
                  breaks = as.numeric(seq(as.POSIXct("2017-04-19"), by = "day",
                                          length = 7)))

enter image description here