### Install dygraphs Package in R Source: https://github.com/rstudio/dygraphs/blob/master/docs/index.html Demonstrates the R command to install the dygraphs package from CRAN. This package is a prerequisite for using the dygraphs charting library within R. ```r install.packages("dygraphs") ``` -------------------------------- ### Install dygraphs and htmlwidgets Packages Source: https://github.com/rstudio/dygraphs/blob/master/README.md Installs the dygraphs R package and its dependency, htmlwidgets, using the devtools package. This is necessary to use the dygraphs charting functionalities. ```R devtools::install_github(c("ramnathv/htmlwidgets", "rstudio/dygraphs")) ``` -------------------------------- ### Basic dygraphs Plot Initialization Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-plot-labels.html A fundamental example of creating an interactive time series plot using the dygraphs package in R. It requires a data frame with a time series column. ```r library(dygraphs) data(AirPassengers) dygraph(AirPassengers) ``` -------------------------------- ### Example: Using dygraphs Bar Chart in R Pipeline Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-custom-plotters.html This R code demonstrates how to use the custom `dyBarChart` function within a dygraph pipeline. It initializes a dygraph with sample data (`ldeaths`), adds a range selector, and then applies the bar chart plotter. This showcases the integration of custom plotters into the standard dygraphs workflow. ```R dygraph(ldeaths) %>% dyRangeSelector() %>% dyBarChart() ``` -------------------------------- ### Dygraphs Ribbon Plugin with JavaScript Parser and Custom Palette Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-ribbon.html This example demonstrates how to use the dyRibbon function with a custom JavaScript parser to generate ribbon data. The parser analyzes raw data, specifically 'Open' and 'Close' values, to create a ribbon data array. A custom color palette is also applied for visual customization. ```javascript parser <- "function(rawData) {\n var openIdx = 1;\n var closeIdx = 4;\n var ribbonData = [];\n\n for (var i = 0; i < rawData.length; i++) {\n var row = rawData[i];\n var open = row[openIdx];\n var close = row[closeIdx];\n\n if (open < close) {\n ribbonData.push(0.5);\n } else if (open > close) {\n ribbonData.push(1);\n } else {\n ribbonData.push(0);\n }\n }\n return ribbonData;\n}" ``` ```r dygraph(SPY[, c("SPY.Open", "SPY.High", "SPY.Low", "SPY.Close")]) %>% dyRibbon(parser = parser, palette = c("#efefef", "#ffe6e6", "#ccebd6")) ``` -------------------------------- ### Configure and Initialize Highlight.js in JavaScript Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-series-highlighting.html This snippet configures and initializes Highlight.js for code highlighting. It ensures proper rendering on page load and completion. Dependencies include the Highlight.js library. ```javascript if (window.hljs) { hljs.configure({languages: []}); hljs.initHighlightingOnLoad(); if (document.readyState && document.readyState === "complete") { window.setTimeout(function() { hljs.initHighlighting(); }, 0); } } ``` -------------------------------- ### Initialize Tabsets on Document Ready in JavaScript Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-series-highlighting.html This snippet initializes tabset functionality using the buildTabsets function when the document is ready. It's commonly used for organizing content within web pages. Dependencies include jQuery and a custom buildTabsets function. ```javascript $(document).ready(function () { window.buildTabsets("TOC"); }); ``` -------------------------------- ### Add Legend Styling Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-plot-labels.html Applies custom styling to the legend in dygraphs plots. This example demonstrates how to set the legend position and appearance. ```r dyLegend(width = 200, show = TRUE, hideOnMouseOut = TRUE) dyLegend(labelsDiv = "legend-custom") ``` -------------------------------- ### Create Straw Broom Charts with dyRebase in R Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-straw-broom.html This R code demonstrates how to create straw broom charts using the dyRebase function. It fetches stock data using quantmod, merges closing prices, and then applies dyRebase with different options (value, percent, none) along with dyRangeSelector for date window selection. The output includes the plotting code and a JSON representation of the chart's configuration. ```R 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) ``` -------------------------------- ### Applying dyCrosshair Plugin in R Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-plugins.html This example demonstrates how to apply the dyCrosshair plugin to a dygraph object in R, composed with other dygraph functions like dyRangeSelector and dyUnzoom. The 'direction' option is set to 'vertical'. ```r dygraph(ldeaths) %>% dyRangeSelector() %>% dyUnzoom() %>% dyCrosshair(direction = "vertical") ``` -------------------------------- ### Dygraphs Stacked Bar Plotter Implementation Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-custom-plotters.html This Javascript plotter function, adapted from Dygraphs examples, is designed for rendering stacked bar charts. It includes a helper function `stackPoints` to manage cumulative values and interpolation for filling gaps. ```javascript /** * Bar Chart plotter is adapted from http://dygraphs.com/tests/plotters.html */ function stackedBarPlotter(e) { //extracting and reducing the Dygraph.stackPoints_ function stackPoints = function(points, cumulativeYval, seriesExtremes, fillMethod) { var lastXval = null; var prevPoint = null; var nextPoint = null; var nextPointIdx = -1; // Find the next stackable point starting from the given index. var updateNextPoint = function(idx) { // If we've previously found a non-NaN point and haven't gone past it yet, // just use that. if (nextPointIdx >= idx) return; // We haven't found a non-NaN point yet or have moved past it, // look towards the right to find a non-NaN point. for (var j = idx; j < points.length; ++j) { // Clear out a previously-found point (if any) since it's no longer // valid, we shouldn't use it for interpolation anymore. nextPoint = null; if (!isNaN(points[j].yval) && points[j].yval !== null) { nextPointIdx = j; nextPoint = points[j]; break; } } }; for (var i = 0; i < points.length; ++i) { var point = points[i]; var xval = point.xval; if (cumulativeYval[xval] === undefined) { cumulativeYval[xval] = 0; } var actualYval = point.yval; if (isNaN(actualYval) || actualYval === null) { if(fillMethod == 'none') { actualYval = 0; } else { // Interpolate/extend for stacking purposes if possible. updateNextPoint(i); if (prevPoint && nextPoint && fillMethod != 'none') { // Use linear interpolation between prevPoint and nextPoint. actualYval = prevPoint.yval + (nextPoint.yval - prevPoint.yval) * ((xval - prevPoint.xval) / (nextPoint.xval - prevPoint.xval)); } else if (prevPoint && fillMethod == 'all') { actualYval = prevPoint.yval; } else if (nextPoint && fillMethod == 'all') { actualYval = nextPoint.yval; } else { actualYval = 0; } } } else { prevPoint = point; } var stackedYval = cumul ``` -------------------------------- ### Dygraph Configuration with R Source: https://github.com/rstudio/dygraphs/blob/master/docs/index.html This snippet demonstrates configuring a dygraph plot using R. It showcases setting plot attributes like labels, axes, series, and interaction models, along with providing sample data. This configuration forms the basis for generating interactive time series charts. ```R library(dygraphs) data <- structure(list(month = c("1974-01-01T00:00:00.000Z", "1974-02-01T00:00:00.000Z", "1974-03-01T00:00:00.000Z", "1974-04-01T00:00:00.000Z", "1974-05-01T00:00:00.000Z", "1974-06-01T00:00:00.000Z", "1974-07-01T00:00:00.000Z", "1974-08-01T00:00:00.000Z", "1974-09-01T00:00:00.000Z", "1974-10-01T00:00:00.000Z", "1974-11-01T00:00:00.000Z", "1974-12-01T00:00:00.000Z", "1975-01-01T00:00:00.000Z", "1975-02-01T00:00:00.000Z", "1975-03-01T00:00:00.000Z", "1975-04-01T00:00:00.000Z", "1975-05-01T00:00:00.000Z", "1975-06-01T00:00:00.000Z", "1975-07-01T00:00:00.000Z", "1975-08-01T00:00:00.000Z", "1975-09-01T00:00:00.000Z", "1975-10-01T00:00:00.000Z", "1975-11-01T00:00:00.000Z", "1975-12-01T00:00:00.000Z", "1976-01-01T00:00:00.000Z", "1976-02-01T00:00:00.000Z", "1976-03-01T00:00:00.000Z", "1976-04-01T00:00:00.000Z", "1976-05-01T00:00:00.000Z", "1976-06-01T00:00:00.000Z", "1976-07-01T00:00:00.000Z", "1976-08-01T00:00:00.000Z", "1976-09-01T00:00:00.000Z", "1976-10-01T00:00:00.000Z", "1976-11-01T00:00:00.000Z", "1976-12-01T00:00:00.000Z", "1977-01-01T00:00:00.000Z", "1977-02-01T00:00:00.000Z", "1977-03-01T00:00:00.000Z", "1977-04-01T00:00:00.000Z", "1977-05-01T00:00:00.000Z", "1977-06-01T00:00:00.000Z", "1977-07-01T00:00:00.000Z", "1977-08-01T00:00:00.000Z", "1977-09-01T00:00:00.000Z", "1977-10-01T00:00:00.000Z", "1977-11-01T00:00:00.000Z", "1977-12-01T00:00:00.000Z", "1978-01-01T00:00:00.000Z", "1978-02-01T00:00:00.000Z", "1978-03-01T00:00:00.000Z", "1978-04-01T00:00:00.000Z", "1978-05-01T00:00:00.000Z", "1978-06-01T00:00:00.000Z", "1978-07-01T00:00:00.000Z", "1978-08-01T00:00:00.000Z", "1978-09-01T00:00:00.000Z", "1978-10-01T00:00:00.000Z", "1978-11-01T00:00:00.000Z", "1978-12-01T00:00:00.000Z", "1979-01-01T00:00:00.000Z", "1979-02-01T00:00:00.000Z", "1979-03-01T00:00:00.000Z", "1979-04-01T00:00:00.000Z", "1979-05-01T00:00:00.000Z", "1979-06-01T00:00:00.000Z", "1979-07-01T00:00:00.000Z", "1979-08-01T00:00:00.000Z", "1979-09-01T00:00:00.000Z", "1979-10-01T00:00:00.000Z", "1979-11-01T00:00:00.000Z", "1979-12-01T00:00:00.000Z"), Male = c(2134, 1863, 1877, 1877, 1492, 1249, 1280, 1131, 1209, 1492, 1621, 1846, 2103, 2137, 2153, 1833, 1403, 1288, 1186, 1133, 1053, 1347, 1545, 2066, 2020, 2750, 2283, 1479, 1189, 1160, 1113, 970, 999, 1208, 1467, 2059, 2240, 1634, 1722, 1801, 1246, 1162, 1087, 1013, 959, 1179, 1229, 1655, 2019, 2284, 1942, 1423, 1340, 1187, 1098, 1004, 970, 1140, 1110, 1812, 2263, 1820, 1846, 1531, 1215, 1075, 1056, 975, 940, 1081, 1294, 1341), Female = c(901, 689, 827, 677, 522, 406, 441, 393, 387, 582, 578, 666, 830, 752, 785, 664, 467, 438, 421, 412, 343, 440, 531, 771, 767, 1141, 896, 532, 447, 420, 376, 330, 357, 445, 546, 764, 862, 660, 663, 643, 502, 392, 411, 348, 387, 385, 411, 638, 796, 853, 737, 546, 530, 446, 431, 362, 387, 430, 425, 679, 821, 785, 727, 612, 478, 429, 405, 379, 393, 411, 487, 574)), class = "data.frame", row.names = c(NA, -75L)) ``` ```R dygraph(data, main = "Monthly Male and Female Counts") %>% dyAxis("x", label = "Month") %>% dyAxis("y", label = "Count") %>% dySeries("Male", label = "Male") %>% dySeries("Female", label = "Female") %>% dyOptions(stackedGraph = TRUE, fillGraph = FALSE, fillAlpha = 0.15) ``` -------------------------------- ### Dygraphs Stacked Bar Plotter Function Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-custom-plotters.html The `stackedBarPlotter` function is responsible for rendering stacked bar charts in Dygraphs. It adapts logic from Dygraphs examples to calculate and draw bars based on series data, handling stacking and interpolation for missing values. ```javascript function stackedBarPlotter(e) { //extracting and reducing the Dygraph.stackPoints_ function stackPoints = function(points, cumulativeYval, seriesExtremes, fillMethod) { var lastXval = null; var prevPoint = null; var nextPoint = null; var nextPointIdx = -1; // Find the next stackable point starting from the given index. var updateNextPoint = function(idx) { // If we've previously found a non-NaN point and haven't gone past it yet, // just use that. if (nextPointIdx >= idx) return; // We haven't found a non-NaN point yet or have moved past it, // look towards the right to find a non-NaN point. for (var j = idx; j < points.length; ++j) { // Clear out a previously-found point (if any) since it's no longer // valid, we shouldn't use it for interpolation anymore. nextPoint = null; if (!isNaN(points[j].yval) && points[j].yval !== null) { nextPointIdx = j; nextPoint = points[j]; break; } } }; for (var i = 0; i < points.length; ++i) { var point = points[i]; var xval = point.xval; if (cumulativeYval[xval] === undefined) { cumulativeYval[xval] = 0; } var actualYval = point.yval; if (isNaN(actualYval) || actualYval === null) { if(fillMethod == 'none') { actualYval = 0; } else { // Interpolate/extend for stacking purposes if possible. updateNextPoint(i); if (prevPoint && nextPoint && fillMethod != 'none') { // Use linear interpolation between prevPoint and nextPoint. actualYval = prevPoint.yval + (nextPoint.yval - prevPoint.yval) * ((xval - prevPoint.xval) / (nextPoint.xval - prevPoint.xval)); } else if (prevPoint && fillMethod == 'all') { actualYval = prevPoint.yval; } else if (nextPoint && fillMethod == 'all') { actualYval = nextPoint.yval; } else { actualYval = 0; } } } else { prevPoint = point; } var stackedYval = cumulativeYval[xval]; if (lastXval != xval) { // If an x-value is repeated, we ignore the duplicates. stackedYval += actualYval; cumulativeYval[xval] = stackedYval; } lastXval = xval; point.yval_stacked = stackedYval; if (stackedYval > seriesExtremes[1]) { seriesExtremes[1] = stackedYval; } if (stackedYval < seriesExtremes[0]) { seriesExtremes[0] = stackedYval; } } }; // BEGIN HEADER BLOCK // This first block can be copied to other plotters to capture the group var g = e.dygraph; var group; var groupIdx = []; var sets = []; var allSets = e.allSeriesPoints; var minIdx = Infinity; var setName = e.setName; var setNames = g.getLabels().slice(1); var groupSetNames = []; var fillColors = []; var strokeColors = g.getColors(); // this next one we use further down, but will be populated in a decreasing loop, // so we'll establish the size in this forward loop so it has the structure to accept // later on. var seriesExtremes = []; var currGroup = g.attr_("group", setName); for (var setIdx = 0; setIdx < allSets.length; setIdx++) { // get the name and group of the current setIdx setName = setNames[setIdx]; group = g.attr_("group", setName); if (group === currGroup) { //save the indv index and the points groupIdx.push(setIdx); sets.push(allSets[setIdx]); groupSetNames.push(setName); fillColors.push(strokeColors[setIdx]); // the aforementioned stuff for later on var tmpExtremes = []; tmpExtremes[0] = Infinity; tmpExtremes[1] = -Infinity; seriesExtremes.push(tmpExtremes); // capturing the min indx helps to ensure we don't render the plotter // multiple times if (setIdx < minIdx) minIdx = setIdx; } } // We'll employ the plotter only on the first of the group if (e.seriesIndex !== minIdx) return; // END HEADER BLOCK var ctx = e.drawingContext; var axis = g.attr_("axis", e.setName); var y_bottom = g.toDomYCoord(0, axis == "y2" ? 1 : 0); // Find the minimum separation between x-values. // This determines the bar width. var min_sep = Infinity; var points = sets[0]; for (var i = 1; i < points.length; i++) { var sep = points[i].canvasx - points[i - 1].canvasx; if (sep < min_sep) min_sep = sep; } var bar_width = Math.floor(2.0 / 3 * min_sep); // set up cumulative recor ``` -------------------------------- ### Shiny Server Logic for dygraphs Rendering Source: https://github.com/rstudio/dygraphs/blob/master/docs/shiny.html This R code sets up the server-side logic for a Shiny application that utilizes dygraphs. It processes input from the UI, generates predictions using Holt-Winters, and renders the dygraph visualization using `renderDygraph`. ```R library(dygraphs) library(datasets) shinyServer(function(input, output) { predicted <- reactive({ hw <- HoltWinters(ldeaths) predict(hw, n.ahead = input$months, prediction.interval = TRUE, level = as.numeric(input$interval)) }) output$dygraph <- renderDygraph({ dygraph(predicted(), main = "Predicted Deaths/Month") %>% dySeries(c("lwr", "fit", "upr"), label = "Deaths") %>% dyOptions(drawGrid = input$showgrid) }) }) ``` -------------------------------- ### Customize Point Shape in Dygraphs Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-series-options.html This example shows how to further customize the appearance of data points in a dygraph chart by specifying a different `pointShape`. Here, 'triangle' is used to change the marker from the default circle. This allows for varied visual representations of data points. ```r dygraph(ldeaths, main = "Deaths from Lung Disease (UK)") %>% dyOptions(drawPoints = TRUE, pointSize = 5, pointShape = "triangle") ``` -------------------------------- ### Customize Dygraphs Axis Display Options Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-axis-options.html This snippet demonstrates customizing dygraphs axis display by disabling the grid for the x-axis, ensuring the y-axis starts at zero using 'includeZero', and changing the color of axis and grid lines. It relies on dygraphs library options. ```javascript new Dygraph(document.getElementById("graphdiv"), data, { drawGrid: false, // Turns off the grid for the x axis includeZero: true, // Ensures the y axis is scaled from zero axisLineColor: "blue", // Changes the color of the axis line gridLineColor: "lightblue" // Changes the color of the grid line }); ``` -------------------------------- ### Activate Navigation Menu Item (JavaScript) Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-ribbon.html This JavaScript code snippet activates the appropriate navigation menu item based on the current page's URL. It runs when the document is ready, extracts the filename from the URL, and adds an 'active' class to the corresponding anchor tag's parent list item. ```javascript $(document).ready(function () {\n // active menu href = window.location.pathname;\n href = href.substr(href.lastIndexOf('/') + 1);\n if (href == "") href = "index.html";\n $('a[href="' + href + '"]').parent().addClass('active');\n}); ``` -------------------------------- ### Add range selector to dygraph (R) Source: https://github.com/rstudio/dygraphs/blob/master/docs/index.html This code snippet shows how to add a range selector to an existing dygraph chart. It builds upon the previous example by piping the 'dyRangeSelector()' function onto the dygraph object, allowing users to zoom into specific time periods. ```r dygraph(lungDeaths) %>% dyRangeSelector() ``` -------------------------------- ### Shiny Server for Dygraphs with Interactive Inputs Source: https://github.com/rstudio/dygraphs/blob/master/docs/shiny.html This R code defines the server logic for a Shiny application using dygraphs. It generates predicted data, renders the dygraph, and crucially, uses reactive expressions to capture and display information from the dygraph's 'date_window' and 'click' input bindings, formatting dates for user readability. ```r library(dygraphs) library(datasets) shinyServer(function(input, output) { predicted <- reactive({ hw <- HoltWinters(ldeaths) predict(hw, n.ahead = input$months, prediction.interval = TRUE, level = as.numeric(input$interval)) }) output$dygraph <- renderDygraph({ dygraph(predicted(), main = "Predicted Deaths/Month") %>% dySeries(c("lwr", "fit", "upr"), label = "Deaths") %>% dyOptions(drawGrid = input$showgrid) }) output$from <- renderText({ strftime(req(input$dygraph_date_window[[1]]), "%d %b %Y") }) output$to <- renderText({ strftime(req(input$dygraph_date_window[[2]]), "%d %b %Y") }) output$clicked <- renderText({ strftime(req(input$dygraph_click$x), "%d %b %Y") }) output$point <- renderText({ paste0('X = ', strftime(req(input$dygraph_click$x_closest_point), "%d %b %Y"), '; Y = ', req(input$dygraph_click$y_closest_point)) }) }) ``` -------------------------------- ### Add Shaded Regions to Dygraphs Charts (R) Source: https://context7.com/rstudio/dygraphs/llms.txt Illustrates how to add shaded regions to dygraphs charts for highlighting specific time periods or value ranges using dyShading. Examples cover shading on the x-axis (time) and y-axis (value). ```r library(dygraphs) # Shade time periods on x-axis dygraph(nhtemp, main = "New Haven Temperatures") %>% dyShading(from = "1920-1-1", to = "1930-1-1", color = "#FFE6E6") %>% dyShading(from = "1940-1-1", to = "1950-1-1", color = "#CCEEFF") # Shade value ranges on y-axis dygraph(nhtemp, main = "New Haven Temperatures") %>% dyShading(from = "48", to = "52", axis = "y", color = "#F0F0F0") %>% dyShading(from = "50", to = "50.1", axis = "y", color = "red") # Multiple shadings for recession periods dygraph(AirPassengers, main = "Air Passengers") %>% dyShading(from = "1949-07-01", to = "1949-10-01") %>% dyShading(from = "1953-07-01", to = "1954-05-01") %>% dyShading(from = "1957-08-01", to = "1958-04-01") ``` -------------------------------- ### Plotting Additional Series with dyCandlestick in R Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-candlestick.html Shows how to plot additional data series alongside a candlestick chart. When dyCandlestick is used, any subsequent data series are plotted using the default line plotter. This example adds a 'Mean' series derived from the first three columns. ```R m <- cbind(m, apply(m[, 1:3], 1, mean)) colnames(m)[5] <- "Mean" dygraph(m) %>% dyCandlestick() ``` -------------------------------- ### Plotting Multiple Stock Series with Dygraphs Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-upper-lower-bars.html This R code snippet demonstrates how to fetch stock data for multiple companies using the quantmod package and then plot them using dygraphs. It specifically shows how to plot each stock's 'Low', 'Close', and 'High' prices as separate series, grouped by stock ticker. ```R library(quantmod) getSymbols(c("MSFT", "HPQ"), from = "2014-06-01", auto.assign=TRUE) ## [1] "MSFT" "HPQ" 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") ``` -------------------------------- ### Trace Back Path for Stacked Area Filling in JavaScript Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-custom-plotters.html This helper function, `traceBackPath`, is designed to draw the path needed to close a shape for filling in stacked graphs. It takes the drawing context, baseline coordinates, and an array of points (`pathBack`) that define the shape's contour, drawing lines from the current position back along this path. ```javascript var traceBackPath = function(ctx, baselineX, baselineY, pathBack) { ctx.lineTo(baselineX, baselineY); for (var i = pathBack.length - 1; i >= 0; i--) { var pt = pathBack[i]; ctx.lineTo(pt[0], pt[1]); } }; ``` -------------------------------- ### Shiny Date Window Input Handling in R Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-range-selector.html Demonstrates how to capture and display the date window selection from a dygraph within a Shiny application. It checks for NULL input and formats the selected date. ```r output$from <- renderText({ if (!is.null(input$dygraph_date_window)) strftime(input$dygraph_date_window[[1]], "%d %b %Y") }) ``` -------------------------------- ### Set Initial Date Window for Dygraph Range Selector in R Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-range-selector.html Shows how to initialize a dygraph with a specific date window pre-selected in the range selector. This is useful for focusing the user's attention on a particular period of the time series. The 'dateWindow' argument accepts a character vector of start and end dates. ```r dygraph(nhtemp, main = "New Haven Temperatures") %>% dyRangeSelector(dateWindow = c("1920-01-01", "1960-01-01")) ``` -------------------------------- ### Add Limit Line to MSFT Share Price Chart (R) Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-event-lines.html This R code snippet fetches Microsoft's stock data using quantmod and then plots it using dygraphs, adding a red limit line at the initial closing price. It requires the quantmod and dygraphs packages. The input is the MSFT stock data, and the output is a dygraph chart with a limit line. ```r quantmod::getSymbols("MSFT", from = "2014-06-01", auto.assign=TRUE) ## [1] "MSFT" dygraph(MSFT[, 4], main = "Microsoft Share Price") %>% dySeries("MSFT.Close", label = "MSFT") %>% dyLimit(as.numeric(MSFT[1, 4]), color = "red") ``` -------------------------------- ### Dygraphs: Implement Second Y Axis for Distinct Value Types (JavaScript) Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-axis-options.html This JavaScript code configures a dygraph to display two series, 'temperature' and 'rainfall', with distinct value types. The 'rainfall' series is assigned to the second Y-axis ('y2') by setting the 'axis' attribute within the 'series' configuration. This setup requires the dygraphs JavaScript library. ```javascript var data = [ ["1980-01-01T00:00:00.000Z", "1980-02-01T00:00:00.000Z", "1980-03-01T00:00:00.000Z", "1980-04-01T00:00:00.000Z", "1980-05-01T00:00:00.000Z", "1980-06-01T00:00:00.000Z", "1980-07-01T00:00:00.000Z", "1980-08-01T00:00:00.000Z", "1980-09-01T00:00:00.000Z", "1980-10-01T00:00:00.000Z", "1980-11-01T00:00:00.000Z", "1980-12-01T00:00:00.000Z"], [7, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6], [49.9, 71.5, 106.4, 129.2, 144, 176, 135.6, 148.5, 216.4, 194.1, 95.6, 54.4] ]; var g = new Dygraph(document.getElementById("graphdiv"), data, { labels: ["month", "temperature", "rainfall"], legend: "auto", retainDateWindow: false, axes: { x: { pixelsPerLabel: 60 }, y: { } }, series: { rainfall: { axis: 'y2' } } }); ``` -------------------------------- ### Basic CSS Styling Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-range-selector.html Provides essential CSS rules for styling elements within the RStudio Dygraphs project. This includes styles for code blocks, headings, tables, layout containers, and images. ```css code { white-space: pre; } pre:not([class]) { background-color: white; } h1 { font-size: 34px; } h1.title { font-size: 38px; } h2 { font-size: 30px; } h3 { font-size: 24px; } h4 { font-size: 18px; } h5 { font-size: 16px; } h6 { font-size: 12px; } .table th:not([align]) { text-align: left; } .main-container { max-width: 940px; margin-left: auto; margin-right: auto; } code { color: inherit; background-color: rgba(0, 0, 0, 0.04); } img { max-width:100%; height: auto; } .tabbed-pane { padding-top: 12px; } .html-widget { margin-bottom: 20px; } button.code-folding-btn:focus { outline: none; } ``` -------------------------------- ### Tabbed Pane Initialization Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-series-options.html This JavaScript code initializes tabbed panes on the page using the buildTabsets function. It ensures that the DOM is ready before executing the function, which is typically used for organizing content within collapsible and navigable sections. ```javascript $(document).ready(function () { window.buildTabsets("TOC"); }); ``` -------------------------------- ### Customize Shading Colors in Dygraphs (R) Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-annotations.html This example shows how to customize the background shading colors for specific time ranges in a dyGraphs chart. It utilizes the 'color' argument within the dyShading function to apply distinct background colors, making the highlighted periods visually differentiated. The 'from' and 'to' parameters require POSIXct compatible inputs. ```R 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") ``` -------------------------------- ### Add Event Lines to Dygraphs Plot in R Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-event-lines.html This R code snippet demonstrates how to create a Dygraphs plot and add event lines to mark specific dates. It uses the `dygraph` package and its `dyEvent` function to add labels for events like troop deployments. The example also shows how to set a main title and configure the y-axis value range to ensure labels are visible. ```r 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") ``` -------------------------------- ### RStudio Viewer Pane Integration for dygraphs Source: https://github.com/rstudio/dygraphs/blob/master/docs/r-console.html This JavaScript code snippet initializes the table of contents for the R Markdown document and manages the active state of the navigation menu based on the current page. It ensures the correct link is highlighted in the ToC. ```javascript $(document).ready(function () { window.buildTabsets("TOC"); }); $(document).ready(function () { // active menu var href = window.location.pathname; href = href.substr(href.lastIndexOf('/') + 1); if (href == "") href = "index.html"; $('a[href="' + href + '"]').parent().addClass('active'); }); ``` -------------------------------- ### R Function Wrapper for dygraphs Unzoom Plugin Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-plugins.html This R function, `dyUnzoom`, acts as a wrapper for the 'Unzoom' dygraphs JavaScript plugin. It utilizes the `dyPlugin` function to register the plugin, making it available for use within an R `dygraphs` pipeline. This allows for programmatic control over adding the 'Reset Zoom' functionality to interactive charts. ```r dyUnzoom <-function(dygraph) { dyPlugin( dygraph = dygraph, name = "Unzoom", path = system.file("plugins/unzoom.js", package = "dygraphs") ) } ``` -------------------------------- ### Configure Series Highlighting in Dygraphs Charts (R) Source: https://context7.com/rstudio/dygraphs/llms.txt Explains how to configure interactive series highlighting in dygraphs charts using dyHighlight. This includes options for circle size, background fade effects, and maintaining highlight visibility when the mouse leaves the chart. ```r library(dygraphs) lungDeaths <- cbind(ldeaths, mdeaths, fdeaths) # Enhanced highlighting with background fade dygraph(lungDeaths, main = "Deaths from Lung Disease (UK)") %>% dyHighlight( highlightCircleSize = 5, highlightSeriesBackgroundAlpha = 0.2, hideOnMouseOut = FALSE ) # Highlight with custom series styling dygraph(lungDeaths, main = "Deaths from Lung Disease (UK)") %>% dyHighlight( highlightCircleSize = 6, highlightSeriesBackgroundAlpha = 0.3, highlightSeriesOpts = list( strokeWidth = 3, strokeBorderWidth = 1, strokeBorderColor = "white" ) ) # Keep highlighting visible when mouse leaves dygraph(AirPassengers) %>% dyHighlight( highlightCircleSize = 4, hideOnMouseOut = FALSE ) ``` -------------------------------- ### JavaScript: dygraphs Plotter Header Initialization Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-custom-plotters.html Initializes variables and gathers data for drawing stacked graphs in dygraphs. It identifies series belonging to the same group and sets up initial structures for storing series data and their respective extremes. This block is designed to be copied for other plotters. ```javascript // BEGIN HEADER BLOCK // This first block can be copied to other plotters to capture the group var g = e.dygraph; var group; var groupIdx = []; var sets = []; var allSets = e.allSeriesPoints; var minIdx = Infinity; var setName = e.setName; var setNames = g.getLabels().slice(1); var groupSetNames = []; var fillColors = []; var strokeColors = g.getColors(); // this next one we use further down, but will be populated in a decreasing loop, // so we'll establish the size in this forward loop so it has the structure to accept // later on. var seriesExtremes = []; var currGroup = g.attr_("group", setName); for (var setIdx = 0; setIdx < allSets.length; setIdx++) { // get the name and group of the current setIdx setName = setNames[setIdx]; group = g.attr_("group", setName); if (group === currGroup) { //save the indv index and the points groupIdx.push(setIdx); sets.push(allSets[setIdx]); groupSetNames.push(setName); fillColors.push(strokeColors[setIdx]); // the aforementioned stuff for later on var tmpExtremes = []; tmpExtremes[0] = Infinity; tmpExtremes[1] = -Infinity; seriesExtremes.push(tmpExtremes); // capturing the min indx helps to ensure we don't render the plotter // multiple times if (setIdx < minIdx) minIdx = setIdx; } } // We'll employ the plotter only on the first of the group if (e.seriesIndex !== minIdx) return; // END HEADER BLOCK ``` -------------------------------- ### Configure Dygraph Display Options in R with dyOptions Source: https://context7.com/rstudio/dygraphs/llms.txt Sets global display settings for dygraphs plots, including fill styles, line styles, colors, and grid options. Supports filled graphs, step plots, stacked graphs, and custom stroke patterns. ```r library(dygraphs) # Filled graph with custom styling dygraph(nhtemp, main = "New Haven Temperatures") %>% dyOptions( fillGraph = TRUE, fillAlpha = 0.4, drawGrid = FALSE, colors = "#D8AE5A" ) # Step plot with points dygraph(presidents) %>% dyOptions( stepPlot = TRUE, drawPoints = TRUE, pointSize = 3, strokeWidth = 2 ) # Stacked graph dygraph(cbind(mdeaths, fdeaths)) %>% dyOptions( stackedGraph = TRUE, fillGraph = TRUE, colors = c("#E69F00", "#56B4E9") ) # Custom stroke patterns dygraph(lungDeaths) %>% dyOptions( strokeWidth = 2, strokePattern = "dashed", drawPoints = TRUE, pointSize = 4 ) ``` -------------------------------- ### Shiny UI for dygraphs Integration Source: https://github.com/rstudio/dygraphs/blob/master/docs/shiny.html This R code defines the user interface for a Shiny application, incorporating a dygraph visualization. It uses `dygraphOutput` to reserve a space for the plot and includes sidebar controls for user interaction. ```R library(dygraphs) shinyUI(fluidPage( titlePanel("Predicted Deaths from Lung Disease (UK)"), sidebarLayout( sidebarPanel( numericInput("months", label = "Months to Predict", value = 72, min = 12, max = 144, step = 12), selectInput("interval", label = "Prediction Interval", choices = c("0.80", "0.90", "0.95", "0.99"), selected = "0.95"), checkboxInput("showgrid", label = "Show Grid", value = TRUE) ), mainPanel( dygraphOutput("dygraph") ) ) )) ``` -------------------------------- ### Activating Table Styles with jQuery (JavaScript) Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-series-highlighting.html This JavaScript code snippet adds Bootstrap table styling to Pandoc-generated tables. It targets table rows with the class 'header' and applies 'table table-condensed' classes to enhance their appearance. This functionality is executed when the DOM is ready. ```javascript function bootstrapStylePandocTables() { $('tr.header').parent('thead').parent('table').addClass('table table-condensed'); } $(document).ready(function () { bootstrapStylePandocTables(); }); ``` -------------------------------- ### Dygraphs Stacked Bar Plotter Initialization and Data Stacking Source: https://github.com/rstudio/dygraphs/blob/master/docs/gallery-custom-plotters.html Initializes variables, gathers series data, and stacks points for the stacked bar chart. It iterates through datasets, applies stacking logic using `stackPoints`, and updates series extremes. This function is crucial for preparing data before plotting. ```javascript var cumulativeYval = []; var packed = g.gatherDatasets_(g.rolledSeries_, null); var extremes = packed.extremes; var seriesName; for (var j = sets.length - 1; j >= 0; j--) { points = sets[j]; seriesName = groupSetNames[j]; // stack the data stackPoints(points, cumulativeYval, seriesExtremes[j], g.getBooleanOption("stackedGraphNaNFill")); extremes[seriesName] = seriesExtremes[j]; } ```