How can I save a networkD3::sankeyNetwork() into a static image automatically via rmarkdown?
Asked Answered
M

1

5

When I write a report in rmarkdown, all my figures as save automatically under the folder graphs. However, as a Sankey diagram is different, it does not save as a picture (.png, etc...) automatically. Is there a workaround for this? (without manually saving each diagram via RStudio Plots panel?)

I saw this question before. But the option from rbokeh produces a low quality graphic. I tried to use the second option, but it seems that there is an error in the code, because the function throws object 'vl' not found.

As that question is from three years ago, I think that there may be a better solution so far.

Example graphic that I want to save:

---
title: "Untitled"
author: "Guilherme"
date: "12/5/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,
                      fig.path = "graph/")
```

```{r}
library(networkD3)
URL <- paste0('https://cdn.rawgit.com/christophergandrud/networkD3/',
              'master/JSONdata/energy.json')
energy <- jsonlite::fromJSON(URL)

# Plot
sankeyNetwork(Links = energy$links, Nodes = energy$nodes, Source = 'source',
             Target = 'target', Value = 'value', NodeID = 'name',
             units = 'TWh', fontSize = 12, nodeWidth = 30)
```
Malarkey answered 5/12, 2020 at 15:1 Comment(1)
is there a way to save as PDF rather than a PNG?Pointed
L
8

What about something like this:

--
title: "sankey as image"
author: "..."
date: "12/5/2020"
output: html_document
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(echo = TRUE,
                      fig.path = "graph/")
```

```{r, fig.align='center'}
library(networkD3)
URL <- paste0('https://cdn.rawgit.com/christophergandrud/networkD3/',
              'master/JSONdata/energy.json')
energy <- jsonlite::fromJSON(URL)

# Plot
sn <- sankeyNetwork(Links = energy$links, Nodes = energy$nodes, Source = 'source',
             Target = 'target', Value = 'value', NodeID = 'name',
             units = 'TWh', fontSize = 12, nodeWidth = 30)

# you save it as an html
saveNetwork(sn, "sn.html")

library(webshot)
# you convert it as png
webshot("sn.html","sn.png", vwidth = 1000, vheight = 900)
```
Lovieloving answered 5/12, 2020 at 17:10 Comment(4)
I was messing with webshot, but couldn't figure it out. I didn't know about the saveNetwork() function, so that was good to learn.Marielamariele
It returns the following error to me: TypeError: Attempting to change the setter of an unconfigurable property. TypeError: Attempting to change the setter of an unconfigurable property. And the screenshot is not takenMalarkey
I reinstall the phantomjs package and it works right nowMalarkey
Same error, and after installing phantomjs.Northerly

© 2022 - 2024 — McMap. All rights reserved.