DataDrivenInvestor

empowerment through data, knowledge, and expertise. subscribe to DDIntel at https://ddintel.datadriveninvestor.com

Follow publication

Interactive time series plots in R

User-configurable graphs with the dygraphs package

Chris Bow
DataDrivenInvestor
Published in
4 min readDec 21, 2018

--

Photo by Markus Spiske on Unsplash

When it comes to plotting data, there often isn’t a ‘one size fits all’ solution. There are usually certain types of graph that fit the data better than others, but, with a static plot, compromises often have to be made in order to show the key message you want to convey from the data.

Given the limitations of static plotting, interactive plots can sometimes be a great solution, giving the end-user of the data the ability to focus on what interests them, which might not be the same thing that interests you.

Interactive plots can provide a useful ‘front-end’ to the data, allowing consumers some freedom and flexibility to quickly and easily explore the data without needing expert knowledge of data wrangling or requiring access to the original dataset. Using web-based plotting methods makes it easy to share findings, and is a great solution for building reporting dashboards.

I’ve been using some of these methods for building an internal marketing analytics dashboard. This allows me to take the raw data, pre-process and summarise and present the key take-home messages, but allow stakeholders to drill into the numbers for a bit more detail, but without getting lost in the large amount of raw data.

One such interactive plotting tool is dygraphs: a JavaScript-based method for plotting time series data. Helpfully, dygraphs is also available as a package for R, so you can produce interactive output as part of your R-based data exploration workflow.

Plotting interactive time series with dygraphs

The dygraphs function in R works with time-series objects, taking a ts or xts dataset as its first argument. For this article, we’ll create a test dataset of two stock prices for for the first eleven months of 2018:

# get stock price data
library(quantmod)
start <- as.Date("2018-01-01")
end <- as.Date("2018-11-30")
getSymbols("AAPL", src = "yahoo", from = start, to = end)
getSymbols("MSFT", src = "yahoo", from = start, to = end)
# extract closing pricesaapl <- AAPL$AAPL.Close
msft <- MSFT$MSFT.Close
# create single datasetstocks <- cbind(aapl, msft)head(stocks) AAPL.Close MSFT.Close
2018-01-02 172.26 85.95
2018-01-03 172.23 86.35
2018-01-04 173.03 87.11
2018-01-05 175.00 88.19
2018-01-08 174.35 88.28
2018-01-09 174.33 88.22
class(stocks)[1] "xts" "zoo"

If we quickly plot our stocks object using ggplot2, we can very quickly see the major trends in the data:

# plot with ggplotlibrary(ggplot2)autoplot(stocks)

If we wanted to drill into the fluctuations a bit more and find the exact date that the price dipped below a particular level, we’d have to go back to our raw data and look there, or replot our figure after filtering the data or changing the limits of the x axis. If we had an interactive plot, we could just zoom in.

To create a basic interactive plot with dygraph is easy, as you can see from the code below. For brevity, I haven’t posted that simple chart here, but you can see how straightforward the function is. For our purposes though, I wanted to illustrate how dygraphs can add additional tools, such as a second y axis (which probably obfuscates things with our test data set, but I wanted to make sure I included this code so I could come back to it later when it was appropriate!), a range selector and an averaging window option.

# create plot using dygraphlibrary(dygraphs)# basic chart
dygraph(stocks)
# customised chartlibrary(dplyr)stock_dyg <- dygraph(stocks, main = "AAPL and MSFT Closing Price 1st Jan - 30th Nov 2018") %>%
dySeries("MSFT.Close", axis = "y2") %>%
dyAxis("y",
label = "AAPL") %>%
dyAxis("y2",
label = "MSFT",
valueRange = c(80, 120),
independentTicks = TRUE) %>%
dyRangeSelector(dateWindow = c("2018-01-01", "2018-11-30")) %>%
dyRoller()
stock_dyg# save as htmllibrary(htmlwidgets)saveWidget(stock_dyg,
"stock_dy.html",
selfcontained = TRUE)

We now have a chart where we can zoom in (double click to zoom back out), smooth the peaks and troughs with our averaging window and get the raw data for each day by hovering. In R Studio the output is rendered immediately in the viewer or, in this case, we’ve saved the output as html using the htmlwidgets package.

Happy interactive graphing and dashboarding!

For further introductions to how you can quickly use data science tools in your business analytics, follow Chris on Twitter.

--

--

Written by Chris Bow

Former immunologist turned data scientist and marketer. Proponent of applying scientific thinking to non-scientific problems. Consultant for Cairney & Company.

Responses (1)

Write a response