Search code examples
rhtmlwidgetsnetworkd3htmltools

How to add title to a networkD3 visualisation when saving as a web page?


I have created a interactive visualisation using the following code:

library(networkD3)

nodes = data.frame("name" = c("node1", "node2","node3", "node4", "node5", "node6", "node7"))
links = as.data.frame(matrix(c(
0,1,7937,
0,2,6990,
0,3,2483,
1,4,2120,
2,4,666,
3,4,282,
1,5,4583,
2,5,5657,
3,5,731,
1,6,1234,
2,6,756,
3,6,1470), byrow = TRUE, ncol = 3))

names(links) = c("source", "target", "value")

sankey <- sankeyNetwork(Links = links, Nodes = nodes,
          Source = "source", Target = "target",
          Value = "value", NodeID = "name",
          fontSize= 12, nodeWidth = 15)'

This is my first time using the networkD3 package (or any interactive package for that matter) and from playing around I found that to keep it interactive it has to be published as a webpage (or is there another way??) but looking through the documentation for the package I can't see a way to add a title or a caption / comments. I want to share this piece of work round so need to explain what each level means on the published webpage ideally


Solution

  • There is no feature built-in to networkD3 to add titles or captions, but you can use functions in the htmlwidgets package to prepend or append content to an htmlwidget. There are numerous options, but for example....

    library(htmlwidgets)
    library(htmltools)
    
    sankey <- htmlwidgets::prependContent(sankey, htmltools::tags$h1("Title"))
    sankey <- htmlwidgets::appendContent(sankey, htmltools::tags$p("Caption"))