Hiếu Nguyễn Phi
Hiếu Nguyễn Phi

Reputation: 37

Plotting time series in R

I'm new in R. I have a set of daily data in this link dropbox. My code is:

#plotting CLOSE
plot.ts(datatest$CLOSE,ylab="Close")

And this is result:

[Graph][2].

Problem is the xlab, I would like to show DATE variable, but it seems to show the order of CLOSE variable. I also try out other commands like ggplot, xyplot etc. but they require converting to data.frame and it's so hard to me.

I would be grateful for some guidance on how to get DATE variable in the Graph.

Thank you so much.

Upvotes: 1

Views: 3087

Answers (3)

Jav
Jav

Reputation: 2313

   dataset$DATE <- as.Date(dataset$DATE, format = "%A, %B %d, %Y")
  • %A - long weekday
  • %B - Full month name
  • %d - two digit date
  • %Y - four digit year

Upvotes: 1

Patrick
Patrick

Reputation: 513

Something like this will do it:

# load data:
theData = read.csv2(file = "sample.csv",header = TRUE,
                    stringsAsFactors = FALSE,sep = ",",
                    colClasses = c("character",rep("numeric",5)),dec=".")

# We want to plot a custom x-axis, so stop the default
# x-axis being drawn usign xaxt="n":
plot(theData$CLOSE,type="l",xaxt="n")

# Lets say you want to put a date label in 8 different locations:
locations = floor(seq(from=1,to=nrow(theData),by=nrow(theData)/8))

# Now draw the x-axis on your plot like this:
axis(side = 1, at = locations, labels=theData$DATE[locations],las=2)

In the above, side=1 means drawing the axis at the bottom. at=locations means we want to show tick labels at the locations given in the locations vector we created earlier. labels=theData$DATE[locations] provides the labels we want to place at the locations where we are putting a label. las=2 means you want to rotate the tick labels. Try las=1 as well for a different rotation.

However, those dates are kind of long, so you may want to create smaller dates like this:

# Convert your long dates to smaller dates like YYYY-MM-DD, and stick
# the results to the end of your data frame.
theData = cbind(theData,
                "FormattedDate"=as.Date(theData$DATE,"%A, %B %e, %Y"))

# Replot and use your smaller dates. (ces.axis=0.8 makes
# the font smaller)
plot(theData$CLOSE,type="l",xaxt="n")
axis(side = 1, at = locations,
     labels=theData$FormattedDate[locations],las=1,cex.axis=0.8)

Finally, you can also use some nice time series packages to create much nicer plots easily:

install.packages("xts")
library(xts)
xtsData = xts(theData[,"OPEN"],order.by = theData[,"FormattedDate"])
plot.zoo(xtsData)
# or
plot.xts(xtsData)

Left is with zoo. Right is with xts

Upvotes: 2

Jan Sila
Jan Sila

Reputation: 1593

try to use

dataset$DATE<-.as.POSIXct(dataset$DATE)

Upvotes: 1

Related Questions