Search code examples
rquantmod

Drawing a Square Line Chart using quantmod


Is there a way to get quantmod to draw a square line chart?

I've tried modifying my time series so that each data point is replicated one second before the next datapoint (hoping this would approximate a square line), but quantmod seems to data on the x axis sequentially & evenly spaces without regard to the actually values of x (i.e. the horizontal space between one point an the next is the same whether the delta-T is 1 second or 1 minute).

I suppose I could convert my timeseries from a sparse to a dense one (one entry per second instead of one entry per change in value), but this seems very kludgy and should be unnecessary.

I'm constructing my time series thus:

library(quantmod)

myNumericVector <- c(3,7,2,9,4)
myDateTimeStrings <- paste("2011-10-31", c("5:26:00", "5:26:10", "5:26:40", "5:26:50", "5:27:00"))
myXts <- xts(myNumericVector, order.by=as.POSIXct(myDateTimeStrings))

And drawing the chart like so:

chartSeries(myXts, type="line", show.grid="true", theme=chartTheme("black"))

To illustrate what I have vs. what I want, the result looks like the blue line below but I'd like something more like the green:

enter image description here

Also, for the curious, here is the code that replicates points in the time series such that the gap between one value and the next are as small as possible:

mySquareDateTimes <- rep(as.POSIXct(myDateTimeStrings),2)[-1]
mySquareDateTimes[seq(2,8,by=2)] <- mySquareDateTimes[seq(2,8,by=2)] - 1
mySquareXts <- xts(rep(myNumericVector,each=2)[-10], order.by=mySquareDateTimes)
chartSeries(mySquareXts, type="line", show.grid="true", theme=chartTheme("black"))

The results are less than ideal.


Solution

  • You want a line.type of "step":

    chartSeries(myXts, line.type="s")
    

    See ?plot, specifically "type" under ... in the Arguments section (you may want "S" instead of "s").