gpt4 book ai didi

javascript - R networkD3包: node coloring in simpleNetwork()

转载 作者:可可西里 更新时间:2023-11-01 02:57:07 25 4
gpt4 key购买 nike

networkD3 包(参见 herehere)允许用户创建简单的交互式网络:

# Load package
library(networkD3)

# Create fake data
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)

# Plot
simpleNetwork(networkData)

有没有办法指定我希望 src 向量中的所有元素都是某种颜色,同时允许 target 向量中的所有元素是不同的颜色?这将使我能够从视觉上区分网络中的 src 节点和 target 节点。

simpleNetwork() 目前似乎不支持此功能(但我希望有人可以用自制脚本帮助我):

enter image description here

一个类似但不相关的问题是 asked here .

最佳答案

下面是如何使用 forceNetwork 控制节点的颜色。请注意,这仍然不会告诉您链接的方向,因为某些节点是某些链接的源和其他链接的目标 - 因此您需要以某种方式重新考虑该逻辑。但无论如何,这里是控制节点的颜色。

# Load package
library(networkD3)
library(dplyr) # to make the joins easier

# Create fake data
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)


# create a data frame of the edges that uses id 0:9 instead of their names
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

# make a grouping variable that will match to colours
nodes$group <- ifelse(nodes$name %in% src, "lions", "tigers")

# simple with default colours
forceNetwork(Links = edges, Nodes = nodes,
Source = "source",
Target = "target",
NodeID ="name",
Group = "group",
Value = "width",
opacity = 0.9,
zoom = TRUE)

# control colours with a JS ordinal scale
# edited 20 May 2017 with updated code from Renal Chesak's answer:
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))

enter image description here

关于javascript - R networkD3包: node coloring in simpleNetwork(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35280218/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com