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

时间:2018-01-05 06:20:10

标签: r layout nodes graph-visualization visnetwork

使用" 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()

Snapshot visual

2 个答案:

答案 0 :(得分:1)

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

# 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 

答案 1 :(得分:1)

使用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()