Introduction
You can use dygraphs plugins to customize the appearance
of dygraphs as well as add new interactive behaviors.
Plugins are extensions to the core dygraphs JavaScript
library and are also written in JavaScript. For additional information
on creating dygraphs plugins see https://github.com/danvk/dygraphs/tree/master/src/plugins.
Once you’ve created a dygraphs plugin you can use the
dyPlugin() function to create an R wrapper function for it.
Examples of R wrappers for two simple dygraphs plugins are
provided below.
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:
dyUnzoom <- function(dygraph) {
dyPlugin(
dygraph = dygraph,
name = "Unzoom",
path = system.file("plugins/unzoom.js", package = "dygraphs")
)
}The plugin can now be used directly within a dygraph()
pipeline along with other dygraphs functions:
dygraph(ldeaths) |>
dyRangeSelector() |>
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().
dyCrosshair <- function(
dygraph,
direction = c("both", "horizontal", "vertical")
) {
dyPlugin(
dygraph = dygraph,
name = "Crosshair",
path = system.file("plugins/crosshair.js", package = "dygraphs"),
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:
dygraph(ldeaths) |>
dyRangeSelector() |>
dyUnzoom() |>
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.