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.
> is.ts(EuStockMarkets)  TRUE > head(EuStockMarkets) DAX SMI CAC FTSE [1,] 1628.75 1678.1 1772.8 2443.6 [2,] 1613.63 1688.5 1750.5 2460.2 [3,] 1606.51 1678.6 1718.0 2448.2 [4,] 1621.04 1684.1 1708.1 2470.4 [5,] 1618.16 1686.6 1723.1 2484.7 [6,] 1610.61 1671.6 1714.3 2466.8 >
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:
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.
> ts.plot(EuStockMarkets, col = 1:4, xlab = "Year", ylab = "Prices", main = "European Stock Indices") > legend("topleft", colnames(EuStockMarkets), lty = 1, col = 1:4, bty = "n") >
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.