Inverse datetime (POSIXct data) time in ggplot

I am trying to plot POSIXct times using ggplot and would like to change the axis, but I am struggling to get it working. I used scale_y_datetime because in my real application it is important that I control the gaps on this axis.

Here is an example of my problem, first with a normal order, and then my attempt to rotate the axis.

 # Some random dates and values to plot 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) ggplot(MyData, aes(x=Value, y=Date)) + geom_point() + scale_y_datetime(limits=c(min(MyData$Date),max(MyData$Date))) 

which produces this: MinMax DateTime Limitations

If I try to change the Y axis by changing the limits, I will lose all gaps and data, for example:

 ggplot(MyData, aes(x=Value, y=Date)) + geom_point() + scale_y_datetime(limits=c(max(MyData$Date),min(MyData$Date))) 

Limitations of MaxMin DateTime

Is there an easy way to change the datetime axis?

+7
r ggplot2
source share
1 answer

With this post from Hadley Wickham, here's how you can get the inverse date-time scale:

 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, inv, breaks, format) } rev_date <- c_trans("reverse", "time") ggplot(MyData, aes(x=Value, y=Date)) + geom_point() + scale_y_continuous(trans = rev_date) 

Here is the plot: enter image description here

+9
source share

All Articles