Reputation: 119
I am using the following data frame in 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
I am using function ggplot to plot the data points and label fixed intervals using 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)
Despite specifying the limits, the x
axis labels are not in order as shown beneath:
Upvotes: 3
Views: 1090
Reputation: 16277
You need to put as.POSIXct(TIME)
in you aes
like so. I had to change your code a bit to fit your limited 3-point data example.
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)
EDIT
You should try to use xts
to transform your data in a time series object. This will order the time correctly. Then, you fortify
it to use with 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)
Upvotes: 1
Reputation: 1795
I would use 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 ")
resulting in:
Upvotes: 0