[This article was first published on R-SquareD, and kindly contributed to R-bloggers]. (You can report issue about the content on this page here)
Want to share your content on R-bloggers? click here if you have a blog, or here if you don't.
…to ggplot some xts objects. –
The xts package is fantastic for time-series data manipulation. You can easily convert to and apply functions to different frequencies, merge with other time series vertically and horizontally, and lag data. These are very helpful features that are cumbersome when working with a data.frame. Unfortunately, if you want to leverage ggplot to produce great looking plots, you cannot use xts objects natively.
It is fairly easy to convert from xts to to a data frame but the key is to get the date into its own column.
I don’t like those four steps to get the price data into an xts object, so just create a personal library function to handle it. You can use the quantmod package which includes a function (getSymbols) to download prices and other data from various sources directly into xts objects. You can also just roll your own.
To use ggplot with this data, we need to convert it back to a data.frame. This is a fairly simple process, but again, we don’t want to continually do it so create a function.
If you want to use the group or facet features of ggplot for each time series in your object, you will need to “stack” the data. There are many ways to do this, but melt from the reshape2 package does a good job.
Those are not very helpful charts, but you should get the idea.
Here is a nice candlestick chart that looks much better and uses the data. It takes a little more data manipulation, but it is worth it.
To leave a comment for the author, please follow the link and comment on their blog: R-SquareD.