更改 networkD3 图的背景颜色

Change background color of networkD3 plot

假设我制作了一个 networkD3 图 - 使用包中的最小示例

#
library(networkD3)

# Load data
data(MisLinks)
data(MisNodes)

# Plot
forceNetwork(Links = MisLinks, Nodes = MisNodes,
            Source = "source", Target = "target",
            Value = "value", NodeID = "name",
            Group = "group", opacity = 0.8)

如果我在浏览器中打开它,我可以使用开发人员工具将正文的背景颜色更改为例如background-color: #DAE3F9;"

有没有办法在不在浏览器中打开的情况下自动将图的背景颜色(从默认白色)定义为另一种颜色?基本上,我们能不能像添加JS函数一样直接在代码中添加CSS?

这是我的技巧。这不是很漂亮,但我在 linkDistance 参数中添加了一个函数来完成肮脏的工作。希望有人最终会提出一个不那么笨拙的解决方案:

forceNetwork(Links = MisLinks, Nodes = MisNodes,
  Source = "source", Target = "target",
  Value = "value", NodeID = "name",
  Group = "group", opacity = 0.8,
  linkDistance = 
    JS('function(){d3.select("body").style("background-color", "#DAE3F9"); return 50;}'))

另一个同样没有吸引力的选项是添加一个 clickAction 参数(例如 clickAction = 'd3.select("body").style("background-color", "#DAE3F9")'),但这只会在用户单击节点时更改背景。

如果可能,我们可以通过多种方式使用 htmltools 的一些帮助。

library(networkD3)

# Load data
data(MisLinks)
data(MisNodes)

# Plot
forceNetwork(Links = MisLinks, Nodes = MisNodes,
             Source = "source", Target = "target",
             Value = "value", NodeID = "name",
             Group = "group", opacity = 0.8)

library(htmltools)

# don't like using the !important modifier
#  but without script not sure there is another way
#  to override the default white background
browsable(
  tagList(
    tags$head(
      tags$style('body{background-color: #DAE3F9 !important}')
    ),
    forceNetwork(Links = MisLinks, Nodes = MisNodes,
                 Source = "source", Target = "target",
                 Value = "value", NodeID = "name",
                 Group = "group", opacity = 0.8)
  )
)

# if you want to limit the background-color to
#  the htmlwidget, we could wrap in tags$div
browsable(
  tags$div(
    style = "background-color:#DAE3F9;",
    forceNetwork(Links = MisLinks, Nodes = MisNodes,
                 Source = "source", Target = "target",
                 Value = "value", NodeID = "name",
                 Group = "group", opacity = 0.8)
  )
)

# if you are ok with script then we
#  we could do something like this
browsable(
  tagList(
    forceNetwork(Links = MisLinks, Nodes = MisNodes,
                 Source = "source", Target = "target",
                 Value = "value", NodeID = "name",
                 Group = "group", opacity = 0.8),
    tags$script(
'
document.body.style.backgroundColor = "#DAE3F9"
'      
    )
  )
)