简体   繁体   中英

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:

[图] [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.

试着用

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

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)

左边是动物园。右边是xts

   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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM