R:将标题添加到 networkD3 图并保存

R: add title to networkD3 plot and save

我有兴趣向使用 NetworkD3 创建的 forceNetwork 图添加标题并使用 magrittr 导出 html。

R: HTML Tag Object help page in order to add a title. Then I was directed to adding htmltool browsable() parameters in the Whosebug 问题中找到了解决方案 - 来自@timelyportfolio 的回答。

下面我提供了一个最小的工作示例,用于添加标题,然后在没有标题的情况下保存网络,最后我 non-working 尝试将两者结合起来。

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

虽然我可以使用 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')

我无法将两者结合起来,但没有收到以下错误。

#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

抱歉,如果这只是一个简单的调试,但我不是程序员。

htmltools::tagList() 函数不像 forceNetwork() 函数那样 return 和 htmlwidget,因此它不会为 networkD3::saveNetwork() 函数输出有效输入.尝试使用 htmlwidgets::prependContent() 添加这样的标题...

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