r语言 - 另存为网页时如何向 networkD3 可视化添加标题?



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

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 包(或任何与此相关的交互式包(,并且通过四处玩耍,我发现要保持它的交互性,它必须作为网页发布(或者有其他方法??(但是浏览包的文档我看不到添加标题或标题/评论的方法。我想分享这项工作,所以需要解释每个级别在发布的网页上的含义,理想情况下

没有内置的功能来networkD3添加标题或说明,但您可以使用htmlwidgets包中的函数将内容前置或追加到htmlwidget。有很多选择,但例如....

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

回应评论时,"我最终使用它来添加标题,但它一直将我的可视化向下推并切断底部。即使另存为网页,此功能也会保持关闭状态。我能阻止这种情况发生吗?

我尝试了添加sankey$ssizePolicy$viewer$fill <- FALSE的建议回复,但是,它使我的sankey比我想要的要小。 我发现您可以在添加 HTML 小部件之前通过添加宽度=(所需宽度(和高度=(所需高度(来调整桑基的宽度和高度,这创造了空间,然后添加标题和注释,正如 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

最新更新