Plotting Financial Time Series Data (Multiple Columns) in R
Let's take one more example of plotting financial time series data. This time we will use the EuStockMarkets
data set that comes by default with R. It contains the daily closing prices of major European stock indices from 1991 to 1998.
Check and Print the Data
Let's first check if the data is a time series and then print a few values from the dataset to get a feel of the data.
1> is.ts(EuStockMarkets)
2[1] TRUE
3> head(EuStockMarkets)
4 DAX SMI CAC FTSE
5[1,] 1628.75 1678.1 1772.8 2443.6
6[2,] 1613.63 1688.5 1750.5 2460.2
7[3,] 1606.51 1678.6 1718.0 2448.2
8[4,] 1621.04 1684.1 1708.1 2470.4
9[5,] 1618.16 1686.6 1723.1 2484.7
10[6,] 1610.61 1671.6 1714.3 2466.8
11>
12
As you can see, the dataset is a time series object and contains prices for 4 indices, namely, DAX, SMI, CAC and FTSE.
Plot the Data
We can plot the data using the plot()
function to create a simple plot which will print all 4 series as shown below:
> plot(EuStockMarkets)

Alternatively we can use the ts.plot()
function to get the same plot but with a common y-axis. This time we are also adding a legend to the chart to make it more user-friendly.
1> ts.plot(EuStockMarkets, col = 1:4, xlab = "Year", ylab = "Prices", main = "European Stock Indices")
2> legend("topleft", colnames(EuStockMarkets), lty = 1, col = 1:4, bty = "n")
3>
4
Notes: col
sets the colors of lines, lty
is the line type, and bty
is for the type of box to be drawn around the legend. n
represents no box.
