Get startedGet started for free

Highlighting events in a time series

You have also learned that it is possible to use the function abline() to add straight lines through an existing plot. Specifically, you can draw a horizontal line to identify a particular date by setting h to a specific Y value, and a vertical line to identify a particular level by setting v to a specific X value:

> abline(h = NULL, v = NULL, ...)

Recall that the index of an xts object are date objects, so the X values of a plot will also contain dates. In this exercise, you will use indexing as well as as.Date("YYYY-MM-DD") and mean() to visually compare the average of the Citigroup stock market prices to its price on January 4, 2016, after it was affected by turbulence in the Chinese stock market.

You are provided with the same dataset data as before. Let's give it a try.

Note: this code requires xts version 0.9-7 to work. You can use remotes::install_version() to install particular versions of packages.

This exercise is part of the course

Visualizing Time Series Data in R

View Course

Exercise instructions

  • Plot the third series in data with the title "Citigroup"
  • Create vert_line, the index of the data point in the "citigroup" data that falls on January 4th, 2016
  • Add a red vertical line at this date using abline(), .index(), and vert_line
  • Create hori_line, the object equal to the average value of the "citigroup" price
  • Add a blue horizontal line at this average value using abline() and hori_line

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

# Plot the "citigroup" time series


# Create vert_line to identify January 4th, 2016 in citigroup
vert_line <- which(index(___) == as.Date(___))

# Add a red vertical line using vert_line
abline(___ = .index(___)[___], col = "red")

# Create hori_line to identify average price of citigroup
hori_line <- ___(___)

# Add a blue horizontal line using hori_line
abline(___ = ___, col = "blue")
Edit and Run Code