How to Save Interactive Charts from Dygraph

How to save interactive charts from dygraph

htmlwidgets have a saveWidget function which lets you save the full visualization out as a standalone (or composite) HTML file.

As Miha said, you can knit them as well.

If you don't need the interactivity (which is unlikely in the case of dygraphs) you can also use SVG Crowbar 2 to save out the SVG from the displayed visualization in a browser.

With regard to the "knitting", here's a sample R Markdown document with a dygraph in it:

---
title: "dygraphs knit example"
author: "Bob Rudis (@hrbrmstr)"
date: "March 17, 2015"
output: html_document
---

```{r}
library(dygraphs)
dygraph(nhtemp, main = "New Haven Temperatures") %>%
dyRangeSelector(dateWindow = c("1920-01-01", "1960-01-01"))
```

Knit that in RStudio and it'll generate a self-contained HTML with the visualization.

How to export graphs generated with the dygraphs package in R to png?

As hrbrmstr suggested in the comments, try using webshot.

library(dygraphs)
sample_dat <- data.frame(1:1000, rnorm(1000))
dygraph(sample_dat)

This produces the following output in my default web browser (safari in this instance):

Sample Image

You will notice in the address bar a path to where the file is temporarily stored on your local drive:

Sample Image

Copy paste that path like in the following:

webshot("file:///var/folders/47/71_55p097y94jptwk6t75f8w0000gn/T/RtmpBPhijO/viewhtml2f836e308321/index.html", 
"dygraph.png")

Also note, you may get the following warning if you don't have PhantomJS installed:

PhantomJS not found. You can install it with
webshot::install_phantomjs(). If it is installed, please make sure the
phantomjs executable can be found via the PATH variable.

...in which case run webshot::install_phantomjs()

Once, webshot has saved it, you will notice a new file saved to your working directory:

Sample Image

Automatically saving interactive graph in R to a specified location as a .html file

Using htmlwidgets package you can do...

library(htmlwidgets)

dir.create("Z:\\new folder")

saveWidget(scatterplot3js(x,y,z, color=rainbow(length(z))),
file="Z:\\new folder\\scatterplot.html")

How to download graphs which are dynamic in R Shiny?

Shiny Modules [*] would be a neat possibility here.

Note. I did not fully understand what you tried with your dynamic checkboxGroup, so I replaced it by a static one. Also I was not quite clear what you want to plot in particular. This is however anyways not crucial to the problem at hand, which can be described as follows

Download a dynamic amount of figures in one file.

So here we go, explanation below.

Setup

library(shiny)
library(dplyr)
library(gridExtra)

d <- data.frame(
year = c(1995, 1995, 1995, 1996, 1996, 1996, 1997, 1997, 1997),
Product_Name = c("Table", "Chair", "Bed", "Table", "Chair", "Bed", "Table",
"Chair", "Bed"),
Product_desc = rep(LETTERS[24:26], each = 3),
Cost = c(1, 2, 3, 4, 2, 3, 4, 5, 6)
)

Shiny Modules

plot_ui <- function(id) {
ns <- NS(id)
plotOutput(ns("graph"))
}

plot_server <- function(input, output, session, my_data, graph_type) {

get_graph <- reactive({
base_plot <- ggplot(my_data,
aes(Product_Name, Cost)) +
theme(strip.placement = "outside") +
theme_bw()
if (graph_type() == "b") {
res <- base_plot +
geom_col(aes(fill = Product_desc),
position = position_dodge(preserve = "single")) +
facet_wrap(~year)
} else if (graph_type() == "p") {
res <- base_plot +
geom_point()
}
res
})

output$graph <- renderPlot({
get_graph()
})

list(graph = get_graph)
}

Main App

ui <- fluidPage(
titlePanel("Modules to the Rescue!"),
sidebarLayout(
sidebarPanel(
radioButtons(
"type",
"Graph Type",
c(Bars = "b", Points = "p")
),
checkboxGroupInput("selector",
"Year",
choices = unique(d$year)),
downloadButton("download", "Download Graphs")
),
mainPanel(div(id = "container", div("test content")))
)
)

server <- function(input, output, session) {

## store active plot handlers
all_plots <- reactiveVal()

## counter to ensure unique ids for the module uis
cnt <- reactiveVal(0)

## when we change selector draw plots anew
observe({
## remove all existing plots
removeUI("#container *", immediate = TRUE, multiple = TRUE)
## for each selection create a new plot
## SIDE EFFECT: create the UI
handlers <- lapply(input$selector, function(x) {
cnt(isolate(cnt()) + 1)
my_dat <- d %>%
dplyr::filter(year == x)
new_id <- paste("plot", isolate(cnt()))
insertUI("#container", ui = plot_ui(new_id))
callModule(plot_server, new_id,
my_data = my_dat,
graph_type = reactive(input$type))
})
all_plots(handlers)
})

output$download <- downloadHandler(
filename = function() {
paste0("plots-", Sys.Date(), ".png")
}, content = function(file) {
my_plots <- all_plots()
ggsave(file,
plot = marrangeGrob(lapply(my_plots, function(handle) handle$graph()),
ncol = 1, nrow = length(my_plots)))
}
)
}

shinyApp(ui, server)

Explanation

(The linked document describes in depth what modules are doing so I focus on I used them, rather on how they work in general.)

  1. We create a module whihc does the plotting for us.
  2. The module creates a reactive which produces the plot.
  3. This reactive is used twice: once in the renderPlot function to render the plot, and once as a return parameter of the module.
  4. In the main app, we keep track about all created modules (all_plots), through which we can communicate with the model and in particular to retrieve the plot.
  5. To draw the plots, we listen to the checkboxGroup and whenever there is a change we dynamically remove all plots, and add them afresh and update all_plots through which we can in the last step retrieve the plots for the downloadHandler.
  6. In the downloadHandler we loop through all plots and use gridExtra::marrange to put all of the ggplots into one file via ggsave.

[*] Note that I still use the old callModule syntax as I have noi yet upgraded shiny.

R create interactive plot with slider which width could be changed like in Google Finance (sizeable time-window)

Have a look at dygraphs and dyRangeSelector().

The dygraphs package is an R interface to the dygraphs JavaScript
charting library. It provides rich facilities for charting time-series
data in R

For more information and examples, have a look at dygraph's github.io:

install.packages("dygraphs")
library(dygraphs)
lungDeaths <- cbind(mdeaths, fdeaths)
dygraph(lungDeaths) %>%
dySeries("mdeaths", label = "Male") %>%
dySeries("fdeaths", label = "Female") %>%
dyOptions(stackedGraph = TRUE) %>%
dyRangeSelector(height = 20)

Which gives:

Sample Image



Related Topics



Leave a reply



Submit