使用 networkD3::forceNetwork() 使用特定颜色为网络中的每个节点添加边框

border each node in a network created using networkD3::forceNetwork() with a specific color

考虑以下网络,节点是否可以使用 中的 forceNetwork 函数基于 MisNodes 数据框中的一列以颜色为边界。它有一个选项可以为边缘着色,但不能为节点边界着色。

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)

假设您的节点数据框有一列包含有效的颜色值,您可以在前面加上自定义 JavaScript 来设置节点边框颜色...

library(networkD3)
library(htmlwidgets)

# Load data
data(MisLinks)
data(MisNodes)

MisNodes$border <- c(rep("#F00", 20), rep("#0F0", 20), rep("#00F", 20), rep("#F00", 17))


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


# add the color column back in to the data in the htmlwidget because
# forceNetwork only passes through the necessary columns
fn$x$nodes$border <- MisNodes$border


# add custom JavaScript to set the node stroke to the color in the border column
fn <- htmlwidgets::onRender(fn, 
  'function(el, x) { d3.selectAll("circle").style("stroke", d => d.border); }')


# display
fn