ggplot中的反向日期时间(POSIXct数据)轴 [英] Reverse datetime (POSIXct data) axis in ggplot
问题描述
我试图用ggplot创建一个POSIXct时间图,并想扭转坐标轴,但我正在努力使其工作。
我一直在使用 scale_y_datetime
,因为在我的真实应用程序中,重要的是我可以控制此轴上的中断。
下面是我的问题的一个例子,首先是正常顺序,然后是我尝试颠倒轴线。
#一些随机日期和值来绘制
迈德特< -
结构(列表(日期=结构(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( 日期, 值),row.names = C(NA,
-10L),类= data.frame)
library(ggplot2)
library(scales)
ggplot(MyDa (b),aes(x = Value,y = Date))+
geom_point()+
scale_y_datetime(limits = c(min(MyData $ Date),max(MyData $ Date)))
产生这种结果:
如果我尝试颠倒Y轴,通过颠倒限制,我会失去所有的中断和数据,如下所示:
ggplot(MyData,aes(x = Value,y = Date))+
geom_point()+
scale_y_datetime(limits = c(max(MyData $ Date),min(MyData $ Date)))
有没有简单的方法来逆转日期时间轴?
I'm trying to create a plot of POSIXct times using ggplot, and would like to reverse the axis, but am struggling to make it work.
I've been using scale_y_datetime
, because in my real application, it's important that I have control of the breaks on this axis.
Here's an example of my problem, first with normal ordering, and then my attempt to reverse 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:
If I attempt to reverse the Y axis, by reversing limits, I lose all breaks and data, like this:
ggplot(MyData, aes(x=Value, y=Date)) +
geom_point() +
scale_y_datetime(limits=c(max(MyData$Date),min(MyData$Date)))
Is there a simple way to reverse the datetime axis?
With the help from this post from Hadley Wickham here is how you can get a reverse datetime 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:
这篇关于ggplot中的反向日期时间(POSIXct数据)轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!