我在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
轴标签的顺序不正确,如下所示:
答案 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)
修改强>
您应该尝试使用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)
答案 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 ")
导致: