首页 > 解决方案 > 在 ggplot 版本 3+ 中反转日期时间(POSIXct 数据)轴

问题描述

试图让ggplot 中的反向日期时间(POSIXct 数据)轴在当前版本(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)

给出错误Error: Invalid input: time_trans works with objects of class POSIXct only 但时间戳属于 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 ...

更新:在创建 myData df 之前加载秤库后所需的结果。 预期和实现的结果

标签: rggplot2

解决方案


这是你想要达到的目标吗?

y 尺度作为时间,最早的时间在底部:

ggplot(myData, aes(y=value, x=timestamp)) +
  geom_path() +
  scale_x_datetime() + 
coord_flip()

在此处输入图像描述

问题中发布的代码对我有用。这是所需的输出:

在此处输入图像描述


推荐阅读