christophergandrud / networkD3

D3 JavaScript Network Graphs from R
http://christophergandrud.github.io/networkD3
650 stars 269 forks source link

Save files to PNG programmatically #219

Closed breschke closed 6 years ago

breschke commented 6 years ago

I don't use RStudio, and I need to create hundreds of PNG files of static graphs on the fly. Is there a way to do this from within R, rather than point-and-click in e.g. RStudio?

cjyetman commented 6 years ago

This is not possible with networkD3 alone and is not likely to be added as a feature, but it can be achieved with other packages, e.g. webshot. Here's an example...

library(networkD3)
library(htmlwidgets)
library(webshot)

data(MisLinks)
data(MisNodes)

# save the htmlwidget created by forceNetwork()
force_widget <- forceNetwork(Links = MisLinks, Nodes = MisNodes, 
                             Source = "source", Target = "target", 
                             Value = "value", NodeID = "name", Group = "group")

# save the widget to a temporary file
html_tmp <- tempfile(fileext = ".html")
htmlwidgets::saveWidget(force_widget, html_tmp)

# use webshot to create a png of the htmlwidget
webshot::webshot(url = html_tmp, selector = "#htmlwidget_container", 
                 file = "force_widget.png")
breschke commented 6 years ago

Works perfectly. Thanks.