x轴上的时间数据在GGR绘图中未排序
我在R中使用以下数据帧x轴上的时间数据在GGR绘图中未排序,r,datetime,ggplot2,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\u x\u datetime标记固定间隔 library(ggplot2) # including necessary libraries lims <- as.POSIXct(st
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\u x\u 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)
library(ggplot2)#包括必要的库
lims您需要像.POSIXct(TIME)
一样将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)
我会使用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 ")
库(data.table)
图书馆(lubridate)
图书馆(GG2)
时间你能把str(open)
的输出张贴在问题的底部吗?它在一开始就已经张贴了。为了避免给对象命名,例如open
(因为它是R
)这看起来可能是一个时区问题。您使用的是ggplot2的最新版本吗?最新版本默认使用附加到变量的时区,但我记得以前的默认值可能会导致问题。可能是重复的@Sahityaridhar不确定您在说什么。在我的示例中,x标签的顺序是从午夜到午夜。在我的示例中,x标签的顺序根本没有改变。这可能是因为数据帧中的差异吗?即使在执行代码时,我也没有正确的标签order@SahityaSridhar我使用xts
进行了编辑,这对时间序列数据非常有效。它还将正确排序数据。否。还是一样的顺序。
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 ")