更改networkD3绘图的背景色
假设我使用包中的最小示例绘制一个networkD3图更改networkD3绘图的背景色,r,networkd3,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",
#
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)
如果我在浏览器中打开它,我可以使用开发人员工具将主体的背景色更改为,例如背景色: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.selectbody.stylebackground-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"
'
)
)
)
哈这是一种非常简洁/有趣的方法——它从未劫持过另一个参数。我认为它工作正常,但也许有更好的方法。我在想这是否会有任何不必要的副作用,但似乎效果不错。@jalapic我很有创意!不确定副作用。FWIW,如果实现了关于更改背景颜色的功能请求,可能会直接实现更好的方法: