Reputation: 145
Trying to get Reverse datetime (POSIXct data) axis in ggplot to work under current versions (R 3.6.2, ggplot 3.2.1).
### THIS NOW WORKS ###
library(lubridate)
library(tidyverse)
library(scales)
# Some random-ish date and values to plot
n <- 3700
myData <- tibble(timestamp = now() + seq(1:n) , value = sin(seq(1:n)/100) + rnorm(n)/10)
# the 'solution' per above link
c_trans <- function(a, b, breaks = b$breaks, format = b$format) {
a <- scales::as.trans(a)
b <- scales::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")
## I would like this output with the y-axis in reverse order (top to bottom) as this is a standard practise in this application.
ggplot(myData, aes(x=value, y=timestamp)) +
geom_path() +
scale_y_continuous( trans=rev_date)
gives error Error: Invalid input: time_trans works with objects of class POSIXct only
But timestamp is of class POSIXct
myData %>% str()
Classes ‘tbl_df’, ‘tbl’ and 'data.frame': 3700 obs. of 2 variables:
$ timestamp: POSIXct, format: "2019-12-31 10:08:00" "2019-12-31 10:08:01" "2019-12-31 10:08:02" "2019-12-31 10:08:03" ...
$ value : num -0.00202 -0.06392 -0.01515 0.11406 0.16945 ...
Update: outcome as desired after loading scales library PRIOR to creating the myData df.
Upvotes: 1
Views: 440
Reputation: 5529
Is this what you're trying to achieve?
y-scale as time, earliest time at the bottom:
ggplot(myData, aes(y=value, x=timestamp)) +
geom_path() +
scale_x_datetime() +
coord_flip()
The code posted in the question works for me. Is this the desired output:
Upvotes: 1