我尝试使用
visNetwork
根据边缘属性对图中的边缘进行着色,但它们始终显示与节点相同的颜色。我做错了什么?
代码:
edges$color <- edges$agreement_num
visNetwork(nodes, edges) %>%
visEdges(arrows = 'from', smooth =T) %>%
visOptions(selectedBy= "com") %>%
visNodes(label = TRUE,scaling = list(label = list(min = 30, max = 50))) %>%
visIgraphLayout(layout = "layout_nicely") %>%
可重现的示例:
nodes <- structure(list(id = c("United States of America", "Canada", "Mexico",
"Peru", "Colombia", "Honduras", "Guatemala", "Nicaragua", "Nigeria",
"Belize"), com = c("5", "5", "5", "5", "5", "5", "5", "5", "5",
"5"), label = c("United States of America", "Canada", "Mexico",
"Peru", "Colombia", "Honduras", "Guatemala", "Nicaragua", "Nigeria",
"Belize"), font.size = c(30, 30, 30, 30, 30, 30, 30, 30, 30,
30), group = c("5", "5", "5", "5", "5", "5", "5", "5", "5", "5"
)), row.names = c("United States of America", "Canada", "Mexico",
"Peru", "Colombia", "Honduras", "Guatemala", "Nicaragua", "Nigeria",
"Belize"), class = "data.frame")
edges <- structure(list(from = c("Canada", "Canada", "United States of America",
"Mexico", "United States of America", "Mexico", "United States of America",
"Canada", "Mexico", "United States of America"), to = c("Antigua and Barbuda",
"Barbados", "Barbados", "Belize", "Belize", "Canada", "Canada",
"China, Taiwan Province of", "China, Taiwan Province of", "China, Taiwan Province of"
), weight = c(171966510.34557, 3894809879.52684, 190168793161.723,
229417909.693992, 56692662824.8982, 713710750.313289, 6240520849382.04,
286476683134.553, 928907970.889569, 14741754565243.3), agreement_num = c(1,
3, 45, 32, 2, 185L, NA, 3, 6, 45), value = c(171966510.34557,
3894809879.52684, 190168793161.723, 229417909.693992, 56692662824.8982,
713710750.313289, 6240520849382.04, 286476683134.553, 928907970.889569,
14741754565243.3)), row.names = c(NA, 10L), class = "data.frame")
您需要将 R 颜色名称、十六进制值或两者的组合分配给颜色列。您可以手动执行此操作,也可以使用
palette()
函数执行此操作。以下是手动操作的方法:
library(visNetwork)
# Determine number of colours required and check for NAs
unique(edges$agreement_num)
# [1] 1 3 45 32 2 185 NA 6
# Create df of colours assigned to unique agreement_num values
colourdf <- data.frame(agreement_num = unique(edges$agreement_num),
color = c("#004949", "#009292", "#ff6db6", "#ffb6db",
"#490092", "#006ddb", NA, "#6db6ff"))
# Join dfs
edges <- merge(edges, colourdf, by = "agreement_num", all.x = TRUE)
visNetwork(nodes, edges) %>%
visEdges(arrows = 'from', smooth = T) %>%
visOptions(selectedBy = "com") %>%
visNodes(label = TRUE,scaling = list(label = list(min = 30, max = 50))) %>%
visIgraphLayout(layout = "layout_nicely")