之前的一篇文章詳細介紹了使用此資料在 ggplot 帖子上反轉時間的解決方案:
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")
這個解決方案:
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)
但是,當我現在嘗試運行此代碼時,出現以下錯誤:錯誤:無效輸入:time_trans works with objects of class POSIXct only
我在 R 版本 4.2.2 上運行此代碼,但找不到解決此問題的解決方案。
我嘗試將我的資料強制轉換為 POSIXct 格式,但圖形仍然以同樣的方式中斷。
uj5u.com熱心網友回復:
您可以稍微修改包中的函式coord_x_datetime以tidyquant反轉 y 軸的日期時間。這是呼叫的函式coord_y_datetime:
coord_y_datetime <- function(xlim = NULL, ylim = NULL, expand = TRUE) {
if (!is.null(ylim)) {
ylim <- lubridate::as_datetime(ylim)
}
ggplot2::coord_cartesian(xlim = xlim, ylim = ylim, expand = expand)
}
這是一個可重現的例子:
library(ggplot2)
ggplot(MyData, aes(x = Value, y = Date))
geom_point()
coord_y_datetime(ylim = c(max(MyData$Date), min(MyData$Date)))

創建于 2022-11-14,使用reprex v2.0.2
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/534935.html
標籤:r图表2posixct
