保存为网页时如何将标题添加到 networkD3 可视化?

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

我使用以下代码创建了交互式可视化:

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)'

这是我第一次使用 networkD3 包(或任何与此相关的交互式包)并且通过玩弄我发现要保持它的交互性它必须作为网页发布(或者有其他方式吗?? ) 但是查看包的文档我看不到添加标题或标题/评论的方法。我想分享这轮工作,所以最好在发布的网页上解释每个级别的含义

built-in 到 networkD3 没有添加标题或说明的功能,但您可以使用 htmlwidgets 包中的功能将内容添加到 htmlwidget.有很多选择,但是例如....

library(htmlwidgets)
library(htmltools)

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

回复评论,"I ended up using this to add a title, but it keeps pushing my viz down and cutting the bottom off. This stays off even when saving as a webpage. Is there anyway I can stop this from happening?"

我尝试了添加 sankey$sizingPolicy$viewer$fill <- FALSE 的建议回复,但是,它使我的 sankey 比我想要的要小。我发现您可以在添加 HTML 小部件之前通过添加 width=(desired width) 和 height=(desired height) 来调整 Sankey 的宽度和高度,然后创建 space按照 CJ Yetman 的建议添加标题和评论。

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

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,
                        width= 900, height=600)


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

sankey