gpt4 book ai didi

R:在 visNetwork 中保留相同的默认颜色集,即使缺少组

转载 作者:行者123 更新时间:2023-12-05 06:15:05 25 4
gpt4 key购买 nike

我想使用 visNetwork 包绘制网络。我希望我的节点在所有不同的网络中对相同的组使用相同的颜色。所以我要

  • A组->蓝色
  • B组->黄色
  • C 组 -> 红色。

这是前 3 个默认颜色。这是第一个简单的例子:

nodes <- data.frame(id = 1:10, label = paste("Label", 1:10), 
group = factor(c("A","B","C", "A","C","C","C","A","A","A"), levels=c("A","B","C")))
visnw <- visNetwork(nodes, edges) %>%
visLegend(position = "right")
visnw

这给出了 enter image description here

但是当我省略 B 组时,即使我指定“组”列是包含 3 个水平的因素,“红色”颜色也会消失,可视化中会忽略这一事实。此外,当第一个元素不是“A”时,它会被打乱得更多。

nodes <- data.frame(id = 1:10, label = paste("Label", 1:10), 
group = factor(c("C","A","C", "A","C","C","C","A","A","A"),c("A","B","C"))) %>%
dplyr::arrange(group) #needed to have A as first group but it doesn't seem to have an effect on the second visualisation
edges <- data.frame(from = c(2,5,10), to = c(1,2,10))
visnw <- visNetwork(nodes, edges) %>%
visLegend(position = "right")
visnw

但是,上面的代码告诉我这是错误的,因为 C 组必须有红色。此外,由于节点 1、3、5、6、7 属于组“C”而不是“A”,因此组被切换。当我省略 arrange() 时,后一个问题不会出现,但是图例在“A”级别的顶部和下方有级别“C”,这不是很好。

enter image description here

我试图编辑 visnw 列表,但这不起作用。

我几乎可以通过为每个组明确定义我想要的颜色来实现我想要的。

visnw <- visNetwork(nodes, edges) %>%
visGroups(groupname = "A", color = "lightblue") %>%
visGroups(groupname = "B", color = "yellow") %>%
visGroups(groupname = "C", color = "red") %>%
visLegend(position = "right")
visnw

这给了我这个可视化:

enter image description here

我更喜欢使用默认颜色,因为我喜欢它们,而且默认方案中的节点上还有一条边,我也应该手动定义它。任何人都知道如何实现这一点?

最佳答案

默认组颜色选项由vis.js提供;你可以看到完整列表here .

基于上面链接中的参数列表,例如,您可以像这样完全复制第一组的默认组样式:

visnw <- visNetwork(nodes, edges) %>%
## 0: blue
visGroups(groupname = "A", color = list(border = "#2B7CE9", background = "#97C2FC", highlight = list(border = "#2B7CE9", background = "#D2E5FF"), hover = list(background = "#2B7CE9", border = "#D2E5FF")))

或者,如果您只想更改显着参数,可以尝试以下操作:

visnw <- visNetwork(nodes, edges) %>%
## 0: blue
visGroups(groupname = "A", color = list(border = "#2B7CE9", background = "#97C2FC")) %>%
## 1: yellow
visGroups(groupname = "B", color = list(border = "#FFA500", background = "#FFFF00")) %>%
## 2: red
visGroups(groupname = "C", color = list(border = "#FA0A10", background = "#FB7E81")) %>%
visLegend(position = "right")
visnw

关于R:在 visNetwork 中保留相同的默认颜色集,即使缺少组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62573408/

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