使用 visNetwork 动态更新 R 中的节点

Using visNetwork to dynamically update nodes in R

下面的快照视觉效果是使用 "visNetwork" 包创建的。我在这里的要求是我必须对边缘进行硬编码,并且在使用 visHierarchicalLayout() 之后,我无法按顺序看到它们,请用动态方法帮助我,这样无论有多少数字,我都能得到连续的数字没有硬编码的订单。谢谢,请帮忙。

library(visNetwork)
nodes <- data.frame(id = 1:7, label = 1:7)
edges <- data.frame(from = c(1,2,3,4,5,6),
                  to = c(2,3,4,5,6,7))
visNetwork(nodes, edges, width = "100%") %>% 
visEdges(arrows = "to") %>% 
visHierarchicalLayout()

如果我对您的问题的理解正确,您希望根据 nodes 数据框中的 id 创建 edges 数据框。这是一种选择。

# Extract the id
num <- nodes$id

# Repeat the numbers
num2 <- rep(num, each = 2)

# Remove the first and last numbers
num3 <- num2[c(-1, -length(num2))]

# Create a data frame
edges <- as.data.frame(matrix(num3, ncol = 2, byrow = TRUE))
names(edges) <- c("from", "to")

edges
#   from to
# 1    1  2
# 2    2  3
# 3    3  4
# 4    4  5
# 5    5  6
# 6    6  7 

使用 level 属性完成这项工作,它根据给定的顺序对齐网络。

library(visNetwork)
nodes <- data.frame(id = 1:7, label = 1:7, level = 1:7)
# Extract the id
num <- nodes$id
# Repeat the numbers
num2 <- rep(num, each = 2)
# Remove the first and last numbers
num3 <- num2[c(-1, -length(num2))]
#Create a data frame
edges <- as.data.frame(matrix(num3, ncol = 2, byrow = TRUE))
names(edges) <- c("from", "to")
visNetwork(nodes, edges, width = "100%") %>% 
visEdges(arrows = "to") %>% 
visHierarchicalLayout()