lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)
dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%
dyOptions(colors = RColorBrewer::brewer.pal(3, “Set2”))
lungDeaths <- cbind(mdeaths, fdeaths)
dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%
dyOptions(stepPlot = TRUE)
dygraph(ldeaths, main = “Deaths from Lung Disease (UK)”) %>%
dyOptions(fillGraph = TRUE, fillAlpha = 0.4)
dygraph(ldeaths, main = “Deaths from Lung Disease (UK)”) %>%
dyOptions(drawPoints = TRUE, pointSize = 2)
dygraph(ldeaths, main = “Deaths from Lung Disease (UK)”) %>%
dyOptions(drawPoints = TRUE, pointSize = 5, pointShape = “triangle”)
dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%
dySeries(“mdeaths”, drawPoints = TRUE, pointShape = “square”, color = “blue”) %>%
dySeries(“fdeaths”, stepPlot = TRUE, fillGraph = TRUE, color = “red”)
dygraph(ldeaths, main = “Deaths from Lung Disease (UK)”) %>%
dySeries(“V1”, strokeWidth = 2, strokePattern = “dashed”)
lungDeaths <- cbind(mdeaths, fdeaths, ldeaths)
dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%
dySeries(“fdeaths”, stepPlot = TRUE, color = “red”) %>%
dyGroup(c(“mdeaths”, “ldeaths”), drawPoints = TRUE, color = c(“blue”, “green”))
When users hover their mouse over series and points on the graph a highlight effect appears on the surface of the graph. You can use the dyHighlight function to customize how the highlighting appears.
In this example we specify a larger circle size for point highlighting as well as more decisively fade the non-highlighted series. We also request that the highlighting persist even after the mouse leaves the graph area.
lungDeaths <- cbind(ldeaths, mdeaths, fdeaths)
dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%
dyHighlight(highlightCircleSize = 5,highlightSeriesBackgroundAlpha = 0.2,hideOnMouseOut = FALSE)
You can also set additional visual options for the highlighted series using highlightSeriesOpts.
This argument takes a list of named series options to apply to just the currently highlighted series (see the dySeries function for the various options that can be set). Here we set the stroke width of highlighted series to 3:
dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%
dyHighlight(highlightSeriesOpts = list(strokeWidth = 3))
dygraph(nhtemp, main = “New Haven Temperatures”) %>%
dyAxis(“y”, label = “Temp (F)”, valueRange = c(40, 60)) %>%
dyOptions(axisLineWidth = 1.5, fillGraph = TRUE, drawGrid = FALSE)
The valueRange is used to set a specific range for the y axis.
The axisLineWidth option specifies a slightly wider pixel width for axis lines.
The fillGraph option specifies that y values should be filled vertically
The drawGrid option turns off the grid for both axes (we’ll demonstrate doing this on a per-axis basis below).
Here’s another example that customizes some other axes properties:
dygraph(AirPassengers, main = “Airline Passengers / Month”) %>%
dyAxis(“x”, drawGrid = FALSE) %>%
dyAxis(“y”, label = “Passengers (Thousands)”) %>%
dyOptions(includeZero = TRUE, axisLineColor = “navy”, gridLineColor = “lightblue”)
The drawGrid option turns off the grid for the x axis
The includeZero option ensures that the y axis is scaled from zero rather than the low-end of it’s range of values.
The axisLineColor and gridLineColor options change the colors of axis and grid lines respectively.
If you are plotting multiple series that have distinct value types you can add a second Y-axis to show a distinct value scale. This is done by setting the independentTicks option for the y2 axis and then assigning one or more series to the y2 axis. For example:
define mts with distinct y-axis scales
temperature <- ts(frequency = 12, start = c(1980, 1),
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))
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))
weather <- cbind(rainfall, temperature)
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)
y=FALSE, y2=TRUE: y2 is the primary axis and the y ticks are aligned to the the ones of y2. (only 1 grid)
y=TRUE, y2=TRUE: Both axis are independent and have their own ticks. (2 grids)
dygraph(weather) %>%
dyAxis(“y”, label = “Temperature (C)”) %>%
dyAxis(“y2”, label = “Rainfall”, independentTicks = TRUE) %>%
dySeries(“rainfall”, axis = ‘y2’)
dygraph(discoveries, main = “Important Discoveries”) %>%
dyAxis(“y”, label = “Discoveries / Year”)
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:
dygraph(nhtemp, main = “New Haven Temperatures”) %>%
dySeries(“V1”, label = “Temperature (F)”) %>%
dyLegend(show = “always”, hideOnMouseOut = FALSE)
dygraph(nhtemp, main = “New Haven Temperatures”) %>%
dySeries(“V1”, label = “Temperature (F)”) %>%
dyLegend(show = “follow”)
lungDeaths <- cbind(ldeaths,mdeaths,fdeaths)
dygraph(lungDeaths, main = “Deaths from Lung Disease (UK)”) %>%
dyLegend(width = 400)
By default dygraphs displays time-series using the time zone of the client workstation. However, you can also choose to use the time zone defined within the underlying xts object using the useDataTimezone option.
For example, consider the following time-series than includes randomly generated values for each 3 hour period of the first day of 2015 (the series is defined using the GMT time zone):
library(xts)
datetimes <- seq.POSIXt(as.POSIXct(“2015-01-01”, tz=“GMT”), as.POSIXct(“2015-01-02”, tz=“GMT”), by=“3 hours”)
values <- rnorm(length(datetimes))
series <- xts(values, order.by = datetimes, tz=“GMT”)
dygraph(series) %>%
dyOptions(labelsUTC = TRUE)
If you’d like to force the series to be rendered using an arbitrary time zone you can use the useDataTimezone option to specify that whatever timezone is used in the underlying xts object should be carried through to the client display.
In this example we specify useDataTimezone and the units are displayed in GMT because that was the time zone used when constructuring the time series:
dygraph(series) %>%
dyOptions(useDataTimezone = TRUE)
.dygraph-title { color: navy; font-weight: bold; }
.dygraph-axis-label { font-size: 11px; }
dygraph(nhtemp, main = “New Haven Temperatures”) %>% dyCSS(“dygraph.css”)
Title: .dygraph-label .dygraph-title
x-axis label: .dygraph-label .dygraph-xlabel
y-axis label: .dygraph-label .dygraph-ylabel
y2-axis label: .dygraph-label .dygraph-y2label
x-axis: .dygraph-axis-label .dygraph-axis-label-x
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.
If you are creating an R Markdown document or Shiny application, you may want to apply your dygraphs CSS globally to the page or application rather than attaching it to each plot. See these links for documentation on how to do this:
R Markdown: http://rmarkdown.rstudio.com/html_document_format.html#custom-css
Shiny: http://shiny.rstudio.com/articles/css.html#add-css-to-the-header-with-includecss
dygraph(nhtemp, main = “New Haven Temperatures”) %>%
dyRangeSelector()
dygraph(nhtemp, main = “New Haven Temperatures”) %>%
dyRangeSelector(dateWindow = c(“1920-01-01”, “1960-01-01”))
Note that the dateWindow parameter should be a two-element vector of POSIXct (or objects that can unambiguously converted to POSIXct).
Several other options affect the appearance of the range selector:
dygraph(nhtemp, main = “New Haven Temperatures”) %>%
dyRangeSelector(height = 20, strokeColor = "")
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:
library(xts)
data(sample_matrix)
m <- tail(sample_matrix, n = 32)
dygraph(m) %>%
dyCandlestick()
m <- cbind(m, apply(m[, 1:3], 1, mean))
colnames(m)[5] <- “Mean”
dygraph(m) %>%
dyCandlestick()
library(xts)
data(sample_matrix)
dygraph(sample_matrix) %>%
dyCandlestick(compress = TRUE)
dygraph(ldeaths, main = “All”, group = “lung-deaths”)
dygraph(mdeaths, main = “Male”, group = “lung-deaths”)
dygraph(fdeaths, main = “Female”, group = “lung-deaths”)
library(quantmod)
tickers <- c(“AAPL”, “MSFT”)
getSymbols(tickers)
closePrices <- do.call(merge, lapply(tickers, function(x) Cl(get(x))))
dateWindow <- c(“2008-01-01”, “2009-01-01”)
dygraph(closePrices, main = “Value”, group = “stock”) %>%
dyRebase(value = 100) %>%
dyRangeSelector(dateWindow = dateWindow)
dygraph(closePrices, main = “Percent”, group = “stock”) %>%
dyRebase(percent = TRUE) %>%
dyRangeSelector(dateWindow = dateWindow)
dygraph(closePrices, main = “None”, group = “stock”) %>%
dyRangeSelector(dateWindow = dateWindow)
In order to smooth out the display of a series you can specify a rollPeriod. This will result in each plotted point representing an average of the number of timestamps specified in the roll period.
The roll period will be displayed in a text box at the bottom-left of the plot so that viewers of the plot are aware of the averaging and so that they can change it if they like.
The dyRoller function adds a roller with a specified roll period:
dygraph(discoveries, main = “Important Discoveries”) %>%
dyRoller(rollPeriod = 5)
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:
dygraph(presidents, main = “Quarterly Presidential Approval Ratings”) %>%
dyAxis(“y”, valueRange = c(0, 100)) %>%
dyAnnotation(“1950-7-1”, text = “A”, tooltip = “Korea”) %>%
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:
presAnnotation <- function(dygraph, x, text) {
dygraph %>%
dyAnnotation(x, text, attachAtBottom = TRUE, width = 60)}
dygraph(presidents, main = “Quarterly Presidential Approval Ratings”) %>%
dyAxis(“y”, valueRange = c(0, 100)) %>%
presAnnotation(“1950-7-1”, text = “Korea”) %>%
presAnnotation(“1965-1-1”, text = “Vietnam”)
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:
dygraph(nhtemp, main = “New Haven Temperatures”) %>%
dyShading(from = “1920-1-1”, to = “1930-1-1”) %>%
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:
dygraph(nhtemp, main = “New Haven Temperatures”) %>%
dySeries(label = “Temp (F)”, color = “black”) %>%
dyShading(from = “1920-1-1”, to = “1930-1-1”, color = “#FFE6E6”) %>%
dyShading(from = “1940-1-1”, to = “1950-1-1”, color = “#CCEBD6”)
quantmod::getSymbols(“MSFT”, from = “2014-06-01”, auto.assign=TRUE)
ret = ROC(MSFT[, 4])
mn = mean(ret, na.rm = TRUE)
std = sd(ret, na.rm = TRUE)
dygraph(ret, main = “Microsoft Share Price”) %>%
dySeries(“MSFT.Close”, label = “MSFT”) %>%
dyShading(from = mn - std, to = mn + std, axis = “y”)
dygraph(presidents, main = “Quarterly Presidential Approval Ratings”) %>%
dyAxis(“y”, valueRange = c(0, 100)) %>%
dyEvent(“1950-6-30”, “Korea”, labelLoc = “bottom”) %>%
dyEvent(“1965-2-09”, “Vietnam”, labelLoc = “bottom”)
quantmod::getSymbols(“MSFT”, from = “2014-06-01”, auto.assign=TRUE)
dygraph(MSFT[, 4], main = “Microsoft Share Price”) %>%
dySeries(“MSFT.Close”, label = “MSFT”) %>%
dyLimit(as.numeric(MSFT[1, 4]), color = “red”)
hw <- HoltWinters(ldeaths)
p <- predict(hw, n.ahead = 72, prediction.interval = TRUE)
dygraph(p, main = “Predicted Lung Deaths (UK)”) %>%
dySeries(c(“lwr”, “fit”, “upr”), label = “Deaths”)
hw <- HoltWinters(ldeaths)
p <- predict(hw, n.ahead = 36, prediction.interval = TRUE)
all <- cbind(ldeaths, p)
dygraph(all, “Deaths from Lung Disease (UK)”) %>%
dySeries(“ldeaths”, label = “Actual”) %>%
dySeries(c(“p.lwr”, “p.fit”, “p.upr”), label = “Predicted”)
library(quantmod)
getSymbols(c(“MSFT”, “HPQ”), from = “2014-06-01”, auto.assign=TRUE)
stocks <- cbind(MSFT[,2:4], HPQ[,2:4])
dygraph(stocks, main = “Microsoft and HP Share Prices”) %>%
dySeries(c(“MSFT.Low”, “MSFT.Close”, “MSFT.High”), label = “MSFT”) %>%
dySeries(c(“HPQ.Low”, “HPQ.Close”, “HPQ.High”), label = “HPQ”)
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.
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”))}
dygraph(ldeaths) %>%
dyRangeSelector() %>%
dyUnzoom()
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)))}
dygraph(ldeaths) %>%
dyRangeSelector() %>%
dyUnzoom() %>%
dyCrosshair(direction = “vertical”)
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.