Here you will find daily news and tutorials about R, contributed by over 750 bloggers.
There are many ways to follow us - By e-mail:On Facebook: If you are an R blogger yourself you are invited to add your own R content feed to this site (Non-English R bloggers should add themselves- here)

(This article was first published on R-SquareD, and kindly contributed to R-bloggers)

…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.

Related

To leave a comment for the author, please follow the link and comment on their blog: R-SquareD.