Get startedGet started for free

Adding an extra series to an existing chart

A great way to visually compare two times series is to display them on the same chart with different scales.

Suppose you already have a plot of mydata. As you saw in the video, you can use lines(mydata2) to add a new time series mydata2 to this existing plot. If you want a scale for this time series on the right side of the plot with equally spaced tick marks, use axis(side, at), where side is an integer specifying which side of the plot the axis should be drawn on, and at is set equal to pretty(mydata2).

Finally, to distinguish these two time series, you can add a legend with the legend() function. Let's examine the one used in the video:

> # x specifies location of legend in plot
> legend(x = "bottomright",
         # legend specifies text label(s)
         legend = c("Stock X", "Stock Y"),
         # col specifies color(s)
         col = c("black", "red"),
         # lty specifies line type(s)
         lty = c(1, 1))

Since there are two time series in the plot, some options in legend() are set to a vector of length two.

In this exercise, you will create a plot and legend for two time series. The same dataset data is provided for you.

This exercise is part of the course

Visualizing Time Series Data in R

View Course

Exercise instructions

  • Plot the "microsoft" series and add the title "Stock prices since 2015"
  • Add the "dow_chemical" series to the chart as a red line using lines()
  • Add an appropriately scaled Y axis on the right side of the chart for the "dow_chemical" data using axis() and pretty()
  • Add an appropriately colored legend in the bottom right corner labeled with the names of the stocks and regular lines

Hands-on interactive exercise

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

# Plot the "microsoft" series


# Add the "dow_chemical" series in red


# Add a Y axis on the right side of the chart


# Add a legend in the bottom right corner

       
       
        
Edit and Run Code