adm
adm

Reputation: 364

R: add title to networkD3 plot and save

I am interested in adding a title to a forceNetwork graph created with NetworkD3 and exporting the html with magrittr.

A solution was found in the R: HTML Tag Object help page in order to add a title. Then I was directed to adding htmltool browsable() parameters in the "Change background color of networkD3 plot" StackOverflow question - answer from @timelyportfolio.

Below I have provided a minimal working example for adding the title, then saving the network without the title, and finally my non-working attempt to combine the two.

library(networkD3)
library(htmltools)

# Load data
data(MisLinks)
data(MisNodes)

# Plot with title in R Viewer
browsable(
  tagList(
    tags$h1("Title"),
      forceNetwork(Links = MisLinks, Nodes = MisNodes,
                   Source = "source", Target = "target",
                   Value = "value", NodeID = "name",
                   Group = "group", opacity = 0.8)
  )
)

While I can save the without the title using magrittr %>%:

library(magrittr)

# Plot and save to Mis.html
forceNetwork(Links = MisLinks, Nodes = MisNodes,
                 Source = "source", Target = "target",
                 Value = "value", NodeID = "name",
                 Group = "group", opacity = 0.8)%>%  
      saveNetwork(file = 'Mis.html')

I am having trouble combining the two without getting the following error.

#Plot with title and save to title_Mis.html
browsable(
  tagList(
    tags$h1("Title"),
      forceNetwork(Links = MisLinks, Nodes = MisNodes,
                   Source = "source", Target = "target",
                   Value = "value", NodeID = "name",
                   Group = "group", opacity = 0.8)
  )
)%>%  
  saveNetwork(file = 'title_Mis.html')

Error in system.file(config, package = package) :
'package' must be of length 1

Apologies, if this is just a simple debug, but I am not a programmer.

Upvotes: 4

Views: 4164

Answers (1)

CJ Yetman
CJ Yetman

Reputation: 8848

The htmltools::tagList() function does not return an htmlwidget as the forceNetwork() function does, so it does not output valid input for the networkD3::saveNetwork() function. Try using htmlwidgets::prependContent() to add the title like this...

library(networkD3)
library(magrittr)
library(htmlwidgets)
library(htmltools)

data(MisLinks)
data(MisNodes)

forceNetwork(Links = MisLinks, Nodes = MisNodes, Source = "source", 
             Target = "target", Value = "value", NodeID = "name",
             Group = "group", opacity = 0.8) %>% 
  htmlwidgets::prependContent(htmltools::tags$h1("Title")) %>% 
  saveNetwork(file = 'title_Mis.html')

Upvotes: 9

Related Questions