以下是如何使用forceNetwork
控制节点颜色的方法。请注意,这仍然无法告诉您链接的方向,因为某些节点是某些链接的源,而其他节点是某些链接的目标 - 所以您需要以某种方式重新考虑该逻辑。但无论如何,以下是控制节点颜色的方法。
library(networkD3)
library(dplyr)
src <- c("A", "A", "A", "A",
"B", "B", "C", "C", "D")
target <- c("B", "C", "D", "J",
"E", "F", "G", "H", "I")
networkData <- data.frame(src, target, stringsAsFactors = FALSE)
nodes <- data.frame(name = unique(c(src, target)), stringsAsFactors = FALSE)
nodes$id <- 0:(nrow(nodes) - 1)
edges <- networkData %>%
left_join(nodes, by = c("src" = "name")) %>%
select(-src) %>%
rename(source = id) %>%
left_join(nodes, by = c("target" = "name")) %>%
select(-target) %>%
rename(target = id)
edges$width <- 1
nodes$group <- ifelse(nodes$name %in% src, "lions", "tigers")
forceNetwork(Links = edges, Nodes = nodes,
Source = "source",
Target = "target",
NodeID ="name",
Group = "group",
Value = "width",
opacity = 0.9,
zoom = TRUE)
ColourScale <- 'd3.scaleOrdinal()
.domain(["lions", "tigers"])
.range(["#FF6900", "#694489"]);'
forceNetwork(Links = edges, Nodes = nodes,
Source = "source",
Target = "target",
NodeID ="name",
Group = "group",
Value = "width",
opacity = 0.9,
zoom = TRUE,
colourScale = JS(ColourScale))
![输入图像描述](https://istack.dev59.com/7MXwd.webp)
forceNetwork()
是否可以?您可以通过 Group 和 JavaScript 比例控制颜色。如果您有兴趣,我可以提供完整的答案。 - Peter Ellis