更改networkD3 plot

时间:2016-03-21 14:29:34

标签: r networkd3

假设我创建了一个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;"

有没有办法自动定义绘图的背景颜色(从默认白色)到另一种颜色,而无需在浏览器中打开?基本上,我们可以直接将CSS添加到代码中,就像我们可以添加JS函数一样吗?

2 个答案:

答案 0 :(得分:5)

如果可能,我们可以通过几种方式使用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"
'      
    )
  )
)

答案 1 :(得分:1)

这是我的黑客攻击。它并不漂亮,但我在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")'),但这只会在用户点击某个节点时更改背景。