Using visNetwork to dynamically update nodes in R

我的未来我决定 提交于 2019-12-02 20:03:03

问题


the below snapshot visual is created using the "visNetwork" package. My requirement here is that I have to hard code the edges and also after using visHierarchicalLayout(), I am not able to see them in order, Please help me with a dynamic approach such that no matter how many numbers, I get consecutive numbers in order without hard code. Thanks and please help.

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


回答1:


Using level attribute does the job, it aligns the network based on the order given.

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



回答2:


If I understand your question correctly, you want to create the edges data frame based on the id in the nodes data frame. Here is one option.

# 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 


来源:https://stackoverflow.com/questions/48108231/using-visnetwork-to-dynamically-update-nodes-in-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!