x轴中的时间数据未在R ggplot中排序

时间:2017-06-15 13:45:21

标签: r datetime ggplot2

我在R

中使用以下数据框
TIME                 PRICE
2013-01-01 23:55:03 446.6167
2013-01-01 23:55:02 441.0114
2013-01-01 23:54:59 446.7600

我使用函数ggplot绘制数据点并使用scale_x_datetime标记固定间隔。

library(ggplot2)  # including necessary libraries
lims <- as.POSIXct(strptime(c("2013-01-01 00:00:00","2013-01-01 23:59:00"), format = "%Y-%m-%d %H:%M:%S"))


ggplot(open,aes(x=TIME,y=PRICE))  
   + geom_point(size = 1.0, color="navy") 
   + xlab("Time") 
   + ylab("Price") 
   + ggtitle("time vs Price ") 
   + scale_x_datetime(breaks = date_breaks("200 min"), minor_breaks=date_breaks("15 min"), labels=date_format("%H:%M:%S"),limits=lims)

尽管指定了限制,但x轴标签的顺序不正确,如下所示:

enter image description here

2 个答案:

答案 0 :(得分:1)

您需要将as.POSIXct(TIME)放在aes中。我不得不稍微更改你的代码以适应你有限的3点数据示例。

open <- read.table(text="TIME                 PRICE
'2013-01-01 23:55:03' 446.6167
'2013-01-01 23:55:02' 441.0114
'2013-01-01 23:54:59' 446.7600",header=TRUE, stringsAsFactors=FALSE)

lims <- as.POSIXct(strptime(c("2013-01-01 00:00:00","2013-01-01 23:59:00"),
                   format = "%Y-%m-%d %H:%M:%S"))

ggplot(open,aes(x=as.POSIXct(TIME),y=PRICE)) +  
geom_point(size = 3.0, color="red")+ 
xlab("Time")+ 
ylab("Price")+ 
ggtitle("time vs Price ")+
scale_x_datetime(breaks = date_breaks("360 min"), 
                 minor_breaks=date_breaks("15 min"), 
                 labels=date_format("%H:%M:%S"),limits=lims)

enter image description here

修改 您应该尝试使用xts转换时间序列对象中的数据。这将正确地订购时间。然后,你将fortify与ggplot2一起使用。

library(xts)
open <- read.table(text="TIME                 PRICE
'2013-01-01 23:55:03' 446.6167
'2013-01-01 23:55:02' 441.0114
'2013-01-01 23:54:59' 446.7600",header=TRUE, stringsAsFactors=FALSE)
open <- xts(open$PRICE,as.POSIXct(open$TIME))
open <- fortify(open)

lims <- as.POSIXct(strptime(c("2013-01-01 00:00:00","2013-01-01 23:59:00"),
                            format = "%Y-%m-%d %H:%M:%S"))

ggplot(open,aes(x=Index,y=open)) +  
geom_point(size = 3.0, color="green")+ 
xlab("Time")+ 
ylab("Price")+ 
ggtitle("time vs Price ")+
scale_x_datetime(breaks = date_breaks("360 min"), 
                 minor_breaks=date_breaks("15 min"), 
                 labels=date_format("%H:%M:%S"),limits=lims)

enter image description here

答案 1 :(得分:0)

我会使用lubridate:

library(data.table)
library(lubridate)
library(ggplot2)
time<-seq(ymd_hms('2013-01-01 00:00:01'),ymd_hms('2013-01-02 23:59:59'), by = '1 min')
price<-sample(length(time))
dt<-data.table(time,price)

ggplot(dt,aes(x=time,y=price))  + geom_point(size = 1.0, color="navy") + xlab("Time") + ylab("Price")  + ggtitle("time vs Price ") 

导致:

enter image description here