11.5 Plot TS

11.5.1 plot.xts

plot(msftSbuxMonthlyPrices, main="Monthly Closing Prices", 
     legend.loc="topleft")

The default plot style in plot.xts() is a single-panel plot with multiple series. You can also create multi-panel plots by setting the optional argument multi.panel = TRUE in the call to plot.xts().

plot(msftSbuxMonthlyPrices, 
     main = "Monthly Closing Prices", 
     multi.panel = TRUE)

Add legend to multiple series using addLegend

plot_data <- reg_data %>% 
    select(eRi, rmrf) %>% 
    xts(order.by = the_group$Date)
plot_data

col_vec <- c("black", "red") # color series
plot.xts(plot_data, col = col_vec, main = "Excess Return on Asset and Market")
addLegend(
  "topright", 
  legend.names = c("eRi", "rmrf"), 
  lty = c(1, 1), 
  lwd = c(2, 2),
  col = col_vec,
  bg = "white", # legend background
  bty = "o",    # box border style, doesn't work
  box.col = "white" # box border color
)

Another example

plot(x = basket[,"SPY.Close"], xlab = "Time", ylab = "Cumulative Return",
main = "Cumulative Returns", ylim = c(0.0, 2.5), major.ticks= "years",
        minor.ticks = FALSE, col = "red")
lines(x = basket[,"QQQ.Close"], col = "darkgreen")
lines(x = basket[,"GDX.Close"], col = "goldenrod")
lines(x = basket[,"DBO.Close"], col = "darkblue")
lines(x = basket[,"VWO.Close"], col = "darkviolet")
legend(x = 'topleft', legend = c("SPY", "QQQ", "GDX", "DBO", "VWO"),
      lty = 1, col = myColors)
  • main.timespan = FALSE to remove the time span label in the top right corner.

plot.xts overrides figure margins set by par. If you want to change figure margins, set it inside plot.xts function.

plot.xts set mar = c(3, 2, 0, 2) by default.

11.5.2 autoplot

For plotting xts objects, especially with multiple columns (data series), the ggplot2 function autoplot() is especially convenient and easy:

facets = NULL: plot all series in one panel.

library(ggplot2)
# all series in one panel
autoplot(msftSbuxDailyPrices, facets = NULL) + 
  ggtitle("Daily Closing Prices") +
  ylab("Closing Price Per Share") +
  xlab("Year")

or produce a multi-panel plot call autoplot() with facets = Series ~ .:

# one panel for each series
autoplot(msftSbuxDailyPrices, facets = Series ~ .) +
  ggtitle("Daily Closing Prices") +
  ylab("Closing Price Per Share") +
  xlab("Year")

More refined setting

Set colors

Use scale_[color | fill | linetype]_manual(values = c("key" = "value"), ...) to set colors/fills/linetypes for different series.

# using autoplot from earlier, I placed it into an object
p <- autoplot(prcomp(df), data = iris, colour = 'Species', shape = 'Species', frame = T)
# then I added on scale_color_manual and scale_fill_manual with the wacky color combos that would never be publishable 
p + 
  scale_fill_manual(values = c("#FF1BB3", "#A7FF5B", "#99554D")) + 
  scale_color_manual(values = c("black", "white", "orange")) 

Set date breaks

scale_x_date can be used to set date breaks and labels on the x-axis.

# auto date breaks every 6 mons
autoplot(plot_data, facets = NULL) +
    scale_color_manual(values = c("black", "red")) +
    scale_x_date(
      date_breaks = "6 month",
      date_labels = "%b %y",
      limits = c(ymd("2014-12-30"), ymd("2021-12-30") )
    )

# explicit date breaks 
autoplot(plot_data, facets = NULL) +
    scale_color_manual(values = c("black", "red")) +
    scale_x_date(
      breaks = seq(from = index(plot_data)[1] %m-% months(1), 
                   to = tail(index(plot_data), 1), 
                   by = "6 month"),
      date_labels = "%b %y",
      limits = c(ymd("2014-12-30"), ymd("2021-12-30") )
    )

Alternatively, you can use zoo functions

  • scale_x_yearmon to set date breaks for monthly data.
  • scale_x_yearqtr to set date breaks for quarterly data.

These functions are more constrained as it requires the index of the xts object to be in yearmon or yearqtr format. Otherwise, you can use zoo::as.yearmon or zoo::as.yearqtr to convert the index to the required format.


Simulate a autocorrelated time series

arima.sim(model, n, sd = 1)

  • model a list with the following elements.

    • order an optional vector of length 3 containing the ARIMA(p, d, q) order

      • p specifies AR order;

        order = c(0, 0, 0) will generate White Noise.

        order = c(2, 0, 0) will generate an AR(2) series.

      • d is the differencing order;

      • q specifies MA order. order = c(0, 0, 2) will generate an MA(2) series.

    The coefficients/parameters must be provided through the elements ar and ma.

    • ar a vector of length p containing the AR(p) coefficients

    • ma a vector of length q containing the MA(q) coefficients

  • n length of simulated time series

  • sd the standard deviation of the Gaussian errors. Defaults to 1.

  • rand.gen = rnorm can specify a function to generate the innovations. Defaults to normal distribution generator.

  • innov = rand.gen(n, ...) can specify your own series of error here.

# AR(1), with rho=0.7
ar.epsilon <- arima.sim(model = list(order = c(1, 0, 0), ar = 0.7), n = 200, sd = 20)

# AR(2), with with parameters 1.5 and -.75
AR <- arima.sim(model = list(order = c(2, 0, 0), ar = c(1.5, -.75)), n = 200) 

# MA(3), with parameters 0.5, 0.4, and 0.2
sim_ma3_05 <- arima.sim(model = list(order = c(0, 0, 3), ma = c(0.5, 0.4, 0.2)), n=200)