Get startedGet started for free

Refresher on xts and the plot() function

1. Refresher on xts and the plot() function

Welcome to Visualizing Time Series Data in R! My name is Arnaud Amsellem, and I’ll be your instructor for this course. There is a fundamental difference between general plot and a times series plot. In a time series plot each value is associated to a time stamp where in a general plot there is no time index, there is no ordering in the data.

2. Refresher on xts

In R there is a special class of objects to handle time series, the xts object. xts stands for eXtensible Time Series and this is a class of data that contains an array of values comprising data often in a matrix form and an index attribute to provide information about the data’s ordering. The index attribute must be a true time object: Date, POSIX Time, timeDate, chron and so on.

3. plot() and plot.xts()

Once you have a time series the obvious question is how to visualize it? In R, the general plot function is plot but for plotting time series plot-dot-xts is used instead. One useful trick to remember is that when the underlying object is a time series object then plot-dot-xts can be abbreviated and plot can be used instead.

4. Using the plot() function

Let's look at an example. my_ts is a time series that you can plot using plot. You can obviously draw a simple chart, but should you want to make it more readable or add specific information to tailor it, the plot function offers many arguments. Probably too many to remember them all, but there are a few that need to be mastered in order to efficiently use R.

5. Using the plot() function

Once you have drawn my_ts the color of the line can be changed with the col argument. There is a small trick here. In order to change the line color without using plot again, you can use the function lines using col equals red to overplot the black line. We will see more about this function in the next chapter. The line thickness can also be adjusted with the lwd argument, and a title can be added with the main argument.

6. Using the plot() function

You can even add a subtitle with the sub argument. There are many more arguments than you could use, I invite you to have a closer look at the R documentation to find out more.

7. Let's practice!

Let's test your knowledge with a quick quiz!