Series Options

Series Colors

  • You can specify an alternate color palette for series lines using the colors option. For example, to choose a palette from RColorBrewer:
  1. lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)

  2. dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%

  3. dyOptions(colors = RColorBrewer::brewer.pal(3, “Set2”))

Step Plots

  • By default dygraphs displays series as a line, you can however plot series as step chart as follows:
  1. lungDeaths <- cbind(mdeaths, fdeaths)

  2. dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%

  3. dyOptions(stepPlot = TRUE)

Filling

  • You can also fill in the area underneath the series as well as customize the alpha value for the filling:
  1. dygraph(ldeaths, main = “Deaths from Lung Disease (UK)”) %>%

  2. dyOptions(fillGraph = TRUE, fillAlpha = 0.4)

Point Display

  • You can include display of the individual points in a series as well as customize the size of the points:
  1. dygraph(ldeaths, main = “Deaths from Lung Disease (UK)”) %>%

  2. dyOptions(drawPoints = TRUE, pointSize = 2)

  • Different point shapes are available as well:
  1. dygraph(ldeaths, main = “Deaths from Lung Disease (UK)”) %>%

  2. dyOptions(drawPoints = TRUE, pointSize = 5, pointShape = “triangle”)

  • The possible parameters for pointShape are: triangle, square, diamond, pentagon, hexagon, circle, star, plus or ex.

Per-Series Options

  • All of the options above can also be set on a per-series basis using the dySeries function. For example:
  1. dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%

  2. dySeries(“mdeaths”, drawPoints = TRUE, pointShape = “square”, color = “blue”) %>%

  3. dySeries(“fdeaths”, stepPlot = TRUE, fillGraph = TRUE, color = “red”)

Line Strokes

  • You can also customize the way that series lines are drawn. Here we draw a wider line with a custom stroke pattern (dashed line):
  1. dygraph(ldeaths, main = “Deaths from Lung Disease (UK)”) %>%

  2. dySeries(“V1”, strokeWidth = 2, strokePattern = “dashed”)

dyGroup

  • With dyGroup you can replicate options across multiple series or pass a vector of values and have it replicate across the series. If arguments differ in length than the number of series named, then the argument will be cycled across the named series.
  1. lungDeaths <- cbind(mdeaths, fdeaths, ldeaths)

  2. dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%

  3. dySeries(“fdeaths”, stepPlot = TRUE, color = “red”) %>%

  4. dyGroup(c(“mdeaths”, “ldeaths”), drawPoints = TRUE, color = c(“blue”, “green”))

Series Highlighting

  1. lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)

  2. dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%

  3. dyHighlight(highlightCircleSize = 5,highlightSeriesBackgroundAlpha = 0.2,hideOnMouseOut = FALSE)

  1. dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%

  2. dyHighlight(highlightSeriesOpts = list(strokeWidth = 3))

Axis Options

  1. dygraph(nhtemp, main = “New Haven Temperatures”) %>%

  2. dyAxis(“y”, label = “Temp (F)”, valueRange = c(40, 60)) %>%

  3. dyOptions(axisLineWidth = 1.5, fillGraph = TRUE, drawGrid = FALSE)

  1. dygraph(AirPassengers, main = “Airline Passengers / Month”) %>%

  2. dyAxis(“x”, drawGrid = FALSE) %>%

  3. dyAxis(“y”, label = “Passengers (Thousands)”) %>%

  4. dyOptions(includeZero = TRUE, axisLineColor = “navy”, gridLineColor = “lightblue”)

  1. The drawGrid option turns off the grid for the x axis

  2. The includeZero option ensures that the y axis is scaled from zero rather than the low-end of it’s range of values.

  3. The axisLineColor and gridLineColor options change the colors of axis and grid lines respectively.

Second Y Axis

  1. temperature <- ts(frequency = 12, start = c(1980, 1),

  2. data = c(7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6))

  3. rainfall <- ts(frequency = 12, start = c(1980, 1), data = c(49.9, 71.5, 106.4, 129.2, 144.0, 176.0, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4))

  4. weather <- cbind(rainfall, temperature)

  1. dygraph(weather) %>% dySeries(“rainfall”, axis = ‘y2’)

Independent Ticks

  • The independentTicks option can be used to determine which axis is primary (and therefore which axis grid lines are aligned with). In order to display the secondary axis scale at least one of the two axes must specify independentTicks = TRUE. Possible combinations include:
  1. y=TRUE, y2=FALSE (default): y is the primary axis and the y2 ticks are aligned to the the ones of y. (only 1 grid)

  2. y=FALSE, y2=TRUE: y2 is the primary axis and the y ticks are aligned to the the ones of y2. (only 1 grid)

  3. y=TRUE, y2=TRUE: Both axis are independent and have their own ticks. (2 grids)

  • In this example we specify that the y2 axis has independent ticks (resulting in a more natural value scale for the axis labels). We also add a label to each Y axis.
  1. dygraph(weather) %>%

  2. dyAxis(“y”, label = “Temperature (C)”) %>%

  3. dyAxis(“y2”, label = “Rainfall”, independentTicks = TRUE) %>%

  4. dySeries(“rainfall”, axis = ‘y2’)

Labels & Legends

Labels

  • You can add labels to a dygraph using the main, ylab and xlab arguments. For example:
  1. dygraph(discoveries, main = “Important Discoveries”, ylab = “Discoveries / Year”)
  • It’s also possible to specify labels as part of a dyAxis definition. For example:
  1. dygraph(discoveries, main = “Important Discoveries”) %>%

  2. dyAxis(“y”, label = “Discoveries / Year”)

  • The appearance of labels can be customized extensively using CSS. See the CSS Label Styling article for additional details.

Legends

  • There are several options available for customizing the appearance and behavior of the plot legend. By default the legend always appears when there are multiple series and only appears on mouseover when there is a single series. By default the legend shows point values when the mouse is over the graph but not when the mouse leaves.

  • Here we override both of these defaults ensuring that the legend is always visible and that point values are still displayed even after the mouse leaves the plot:

  1. dygraph(nhtemp, main = “New Haven Temperatures”) %>%

  2. dySeries(“V1”, label = “Temperature (F)”) %>%

  3. dyLegend(show = “always”, hideOnMouseOut = FALSE)

  • Here we enable “follow” mode which will show the legend overlaid on the plot (near the mouse) only when the mouse is over a point:
  1. dygraph(nhtemp, main = “New Haven Temperatures”) %>%

  2. dySeries(“V1”, label = “Temperature (F)”) %>%

  3. dyLegend(show = “follow”)

  • When you have several data series sometime the legend mouse-over wraps to a second line. To avoid this you can set the legend width to something wider than the default of 250 pixels. For example:
  1. lungDeaths <- cbind(ldeaths,mdeaths,fdeaths)

  2. dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%

  3. dyLegend(width = 400)

Time Zones

  1. library(xts)

  2. datetimes <- seq.POSIXt(as.POSIXct(“2015-01-01”, tz=“GMT”), as.POSIXct(“2015-01-02”, tz=“GMT”), by=“3 hours”)

  3. values <- rnorm(length(datetimes))

  4. series <- xts(values, order.by = datetimes, tz=“GMT”)

  1. dygraph(series)
  1. dygraph(series) %>%

  2. dyOptions(labelsUTC = TRUE)

  1. dygraph(series) %>%

  2. dyOptions(useDataTimezone = TRUE)

CSS Styling

  1. .dygraph-title { color: navy; font-weight: bold; }

  2. .dygraph-axis-label { font-size: 11px; }

  3. dygraph(nhtemp, main = “New Haven Temperatures”) %>% dyCSS(“dygraph.css”)

CSS Classes

  • The CSS classes for the chart labels are:
  1. Title: .dygraph-label .dygraph-title

  2. x-axis label: .dygraph-label .dygraph-xlabel

  3. y-axis label: .dygraph-label .dygraph-ylabel

  4. y2-axis label: .dygraph-label .dygraph-y2label

  • The axis labels also get CSS classes:
  1. x-axis: .dygraph-axis-label .dygraph-axis-label-x

  2. y-axis: .dygraph-axis-label .dygraph-axis-label-y

3.y2-axis: .dygraph-axis-label .dygraph-axis-label-y .dygraph-axis-label-y2

  • The legend has the .dygraph-legend class. When using highlightSeriesOpts, the selected series’ gets a .highlight class. This can be used to show only a single series in the legend.

  • The full reference to the various CSS classes used throughout a dygraph is here: http://dygraphs.com/css.html.

Applying Styles Globally

Range Selector

  1. dygraph(nhtemp, main = “New Haven Temperatures”) %>%

  2. dyRangeSelector()

  1. dygraph(nhtemp, main = “New Haven Temperatures”) %>%

  2. dyRangeSelector(dateWindow = c(“1920-01-01”, “1960-01-01”))

  1. dygraph(nhtemp, main = “New Haven Temperatures”) %>%

  2. dyRangeSelector(height = 20, strokeColor = "")

Shiny Date Input

  • Shiny applications can respond to changes in the dateWindow via a special date_window input value. For example, if the output id of a dygraph is series then the current date window can be read from input$series_date_window as an array of two date values (from and to).

  • Note that when using the data window input variable you should always check for NULL before accessing it, for example:

  1. output$from <- renderText({
  2. if (!is.null(input$dygraph_date_window))
  3. strftime(input$dygraph_date_window[[1]], “%d %b %Y”) })
  • See the documentation on using dygraphs with Shiny for a more complete example.

Candlestick Charts

  1. library(xts)

  2. data(sample_matrix)

  3. m <- tail(sample_matrix, n = 32)

  4. dygraph(m) %>%

  5. dyCandlestick()

  1. m <- cbind(m, apply(m[, 1:3], 1, mean))

  2. colnames(m)[5] <- “Mean”

  3. dygraph(m) %>%

  4. dyCandlestick()

  1. library(xts)

  2. data(sample_matrix)

  3. dygraph(sample_matrix) %>%

  4. dyCandlestick(compress = TRUE)

Synchronization

  1. dygraph(ldeaths, main = “All”, group = “lung-deaths”)

  2. dygraph(mdeaths, main = “Male”, group = “lung-deaths”)

  3. dygraph(fdeaths, main = “Female”, group = “lung-deaths”)

Straw Broom Charts

  1. library(quantmod)

  2. tickers <- c(“AAPL”, “MSFT”)

  3. getSymbols(tickers)

  4. closePrices <- do.call(merge, lapply(tickers, function(x) Cl(get(x))))

  5. dateWindow <- c(“2008-01-01”, “2009-01-01”)

  6. dygraph(closePrices, main = “Value”, group = “stock”) %>%

  7. dyRebase(value = 100) %>%

  8. dyRangeSelector(dateWindow = dateWindow)

  9. dygraph(closePrices, main = “Percent”, group = “stock”) %>%

  10. dyRebase(percent = TRUE) %>%

  11. dyRangeSelector(dateWindow = dateWindow)

  12. dygraph(closePrices, main = “None”, group = “stock”) %>%

  13. dyRangeSelector(dateWindow = dateWindow)

Roll Periods

  1. dygraph(discoveries, main = “Important Discoveries”) %>%

  2. dyRoller(rollPeriod = 5)

Annotation & Shading

Annotations

  • You can add annotations to individual points within a plot. To minimize their visual footprint annotations are typically short abbreviations (e.g. “A”, “B”, “C”) which are elaborated upon in a tooltip or with adjacent explanatory text.

  • For example, in the following graph we annotate the dates which saw the first deployment of US combat troops to Korea and Vietnam:

  1. dygraph(presidents, main = “Quarterly Presidential Approval Ratings”) %>%

  2. dyAxis(“y”, valueRange = c(0, 100)) %>%

  3. dyAnnotation(“1950-7-1”, text = “A”, tooltip = “Korea”) %>%

  4. dyAnnotation(“1965-1-1”, text = “B”, tooltip = “Vietnam”)

  • There’s a very important aspect of this example to note: the actual dates of the two events are not used for the annotation. Rather, dates that align with the quarterly boundaries of the time series are used (this is because dygraphs will only include annotations that exactly match one of it’s x-axis values).

  • Note that if you want to print a larger annotation and attach it to the x-axis rather than individual points you can use the attachAtBottom and width parameters as follows:

  1. presAnnotation <- function(dygraph, x, text) {

  2. dygraph %>%

  3. dyAnnotation(x, text, attachAtBottom = TRUE, width = 60)}

  4. dygraph(presidents, main = “Quarterly Presidential Approval Ratings”) %>%

  5. dyAxis(“y”, valueRange = c(0, 100)) %>%

  6. presAnnotation(“1950-7-1”, text = “Korea”) %>%

  7. presAnnotation(“1965-1-1”, text = “Vietnam”)

  • This example also demonstrates another concept: writing a helper function to define common graph element options in a single place. The presAnnotation function takes a dygraph and then modifies it to include an annotation with the requisite layout behavior.

Shading

  • You can add a shading effect to the graph background for one or more time ranges. This is useful for highlighting periods of time with special properties (e.g. holding periods for securities).

  • For example, the following code adds a shading effect to the 1920’s and 1940’s for the New Haven Temperatures graph:

  1. dygraph(nhtemp, main = “New Haven Temperatures”) %>%

  2. dyShading(from = “1920-1-1”, to = “1930-1-1”) %>%

  3. dyShading(from = “1940-1-1”, to = “1950-1-1”)

  • Note that the from and to parameters must be of type POSIXct (or objects that are directly convertible to POSIXct).

  • You may want to modify the color of the shading to make it more or less subtle. Here’s a version of the previous graph with custom colors for each shading:

  1. dygraph(nhtemp, main = “New Haven Temperatures”) %>%

  2. dySeries(label = “Temp (F)”, color = “black”) %>%

  3. dyShading(from = “1920-1-1”, to = “1930-1-1”, color = “#FFE6E6”) %>%

  4. dyShading(from = “1940-1-1”, to = “1950-1-1”, color = “#CCEBD6”)

  • Note that we also changed the color of the series to black so that it contrast well with the custom background colors.

Horizontal Shading

  • It is also possible to add horizontal shading to a chart. In the example below, shading is used to show the one standard deviation range for a stock return series.
  1. quantmod::getSymbols(“MSFT”, from = “2014-06-01”, auto.assign=TRUE)

  2. ret = ROC(MSFT[, 4])

  3. mn = mean(ret, na.rm = TRUE)

  4. std = sd(ret, na.rm = TRUE)

  5. dygraph(ret, main = “Microsoft Share Price”) %>%

  6. dySeries(“MSFT.Close”, label = “MSFT”) %>%

  7. dyShading(from = mn - std, to = mn + std, axis = “y”)

Events and Limits

Event Lines

  • Event lines are a useful way to note points within a time series where noteworthy events occurred. For example, in the following graph we overlay the dates which saw the first deployment of US combat troops to Korea and Vietnam over a plot of US presidential approval ratings:
  1. dygraph(presidents, main = “Quarterly Presidential Approval Ratings”) %>%

  2. dyAxis(“y”, valueRange = c(0, 100)) %>%

  3. dyEvent(“1950-6-30”, “Korea”, labelLoc = “bottom”) %>%

  4. dyEvent(“1965-2-09”, “Vietnam”, labelLoc = “bottom”)

  • Note that we specify that our event labels go at the bottom of the graph so they don’t interfere with the legend, and set the y-axis valueRange to ensure that there is adequate room at the bottom for the labels.

Limit Lines

  • Related to event lines are limit lines, which can be used to highlight data levels. For example, one could use limit lines to highlight the initial value of a stock price series.
  1. quantmod::getSymbols(“MSFT”, from = “2014-06-01”, auto.assign=TRUE)

  2. dygraph(MSFT[, 4], main = “Microsoft Share Price”) %>%

  3. dySeries(“MSFT.Close”, label = “MSFT”) %>%

  4. dyLimit(as.numeric(MSFT[1, 4]), color = “red”)

Upper/Lower Bars

  1. hw <- HoltWinters(ldeaths)

  2. p <- predict(hw, n.ahead = 72, prediction.interval = TRUE)

  3. dygraph(p, main = “Predicted Lung Deaths (UK)”) %>%

  4. dySeries(c(“lwr”, “fit”, “upr”), label = “Deaths”)

  1. hw <- HoltWinters(ldeaths)

  2. p <- predict(hw, n.ahead = 36, prediction.interval = TRUE)

  3. all <- cbind(ldeaths, p)

  4. dygraph(all, “Deaths from Lung Disease (UK)”) %>%

  5. dySeries(“ldeaths”, label = “Actual”) %>%

  6. dySeries(c(“p.lwr”, “p.fit”, “p.upr”), label = “Predicted”)

  1. library(quantmod)

  2. getSymbols(c(“MSFT”, “HPQ”), from = “2014-06-01”, auto.assign=TRUE)

  3. stocks <- cbind(MSFT[,2:4], HPQ[,2:4])

  4. dygraph(stocks, main = “Microsoft and HP Share Prices”) %>%

  5. dySeries(c(“MSFT.Low”, “MSFT.Close”, “MSFT.High”), label = “MSFT”) %>%

  6. dySeries(c(“HPQ.Low”, “HPQ.Close”, “HPQ.High”), label = “HPQ”)

Plugins

Simple Example

  • The “Unzoom” dygraphs plugin adds a “Reset Zoom” button to the graph when it’s displaying in a zoomed state (this is a bit more discoverable than the default double-click gesture for unzooming). The JavaScript source code for the Unzoom plugin is here: https://github.com/rstudio/dygraphs/blob/master/inst/plugins/unzoom.js.

  • Here’s how you’d create an R function to wrap the unzoom plugin:

  1. dyUnzoom <-function(dygraph) {

  2. dyPlugin(

  3. dygraph = dygraph,

  4. name = “Unzoom”,

  5. path = system.file(“plugins/unzoom.js”, package = “dygraphs”))}

  • The plugin can now be used directly within a dygraph pipeline along with other dygraphs functions:
  1. dygraph(ldeaths) %>%

  2. dyRangeSelector() %>%

  3. dyUnzoom()

  • Try zooming the dygraph and note that a “Reset Zoom” button now appears when the graph is in the zoomed state.

Plugin Options

  • The dyCrosshair plugin draws a crosshair line over the point closest to the mouse when the user hovers over the graph (see the JavaScript source code for the plugin here: https://github.com/rstudio/dygraphs/blob/master/inst/plugins/crosshair.js). The plugin includes a “direction” option that is provided as an argument to the R wrapper function and then forwarded to the plugin using the “options” argument to dyPlugin.
  1. dyCrosshair <- function(dygraph, direction = c(“both”, “horizontal”, “vertical”)) {

  2. dyPlugin(

  3. dygraph = dygraph,

  4. name = “Crosshair”,

  5. path = system.file(“plugins/crosshair.js”, package = “dygraphs”),

  6. options = list(direction = match.arg(direction)))}

  • The plugin can now be used just like any other dygraphs function and can even be composed with other plugins:
  1. dygraph(ldeaths) %>%

  2. dyRangeSelector() %>%

  3. dyUnzoom() %>%

  4. dyCrosshair(direction = “vertical”)

  • If you hover over the graph you’ll see a vertical crosshair drawn at the current position of the mouse.

Distributing Plugins

  • Plugins for the dygraphs R package consist of a JavaScript source file and an R function that wraps it. If you want to distribute a plugin to other users you should create an R package that includes the JavaScript source file and the R function wrapper. The full path to the plugin’s JavaScript source file should be passed to dyPlugin using the system.file function as illustrated in both of the examples above.

  • If you’ve created a plugin that you think is of broad interest to other users please feel free to submit a pull request to incorporate it directly into the dygraphs package.