我用以下数据创建了一个图形网络:
#关系数据
Data_I_Have <- data.frame(
"Node_A" = c("John", "John", "John", "Peter", "Peter", "Peter", "Tim", "Kevin", "Adam", "Adam", "Xavier"),
"Node_B" = c("Claude", "Peter", "Tim", "Tim", "Claude", "Henry", "Kevin", "Claude", "Tim", "Henry", "Claude"),
" Place_Where_They_Met" = c("Chicago", "Boston", "Seattle", "Boston", "Paris", "Paris", "Chicago", "London", "Chicago", "London", "Paris"),
"Years_They_Have_Known_Each_Other" = c("10", "10", "1", "5", "2", "8", "7", "10", "3", "3", "5"),
"What_They_Have_In_Common" = c("Sports", "Movies", "Computers", "Computers", "Video Games", "Sports", "Movies", "Computers", "Sports", "Sports", "Video Games")
)
#个人数据
additional_data_about_people <- data.frame(
"Person" = c("John", "Peter", "Tim", "Kevin", "Adam", "Xacier", "Claude", "Henry"),
"Job" = c("Teacher", "Lawyer", "Accountant", "Engineer", "Teacher", "Lawyer", "Engineer", "Lawyer"),
"Age" = c("50", "51", "61", "56", "65", "65", "54", "50"),
"Favorite_Food" = c("pizza", "pizza", "tacos", "pizza", "ice cream", "sushi", "sushi", "pizza")
)
library(igraph)
library(dplyr)
library(visNetwork)
graph_file <- data.frame(Data_I_Have$Node_A, Data_I_Have$Node_B)
colnames(graph_file) <- c("Data_I_Have$Node_A", "Data_I_Have$Node_B")
graph <- graph.data.frame(graph_file, directed=F)
graph <- simplify(graph)
plot(graph)
nodes <- data.frame(id = V(graph)$name, title = V(graph)$name)
nodes <- nodes[order(nodes$id, decreasing = F),]
edges <- get.data.frame(graph, what="edges")[1:2]
visNetwork(nodes, edges) %>% visIgraphLayout(layout = "layout_with_fr") %>%
visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)
在visnetwork中,有人知道我如何将"John“的颜色更改为红色吗?
我知道如何在igraph中做到这一点:
V(graph)["John"]$color<-"red"
但是,有人知道如何在visnetwork中做到这一点吗?
谢谢
发布于 2020-11-24 03:28:37
您可以向节点添加color
列:
nodes <- data.frame(id = V(graph)$name, title = V(graph)$name)
nodes <- nodes[order(nodes$id, decreasing = F),]
John_ind <- which(nodes$id == "John")
colours <- rep("lightblue", nrow(nodes)); colours[John_ind] <- "red"
nodes <- cbind(nodes, color = colours)
edges <- get.data.frame(graph, what="edges")[1:2]
visNetwork(nodes, edges) %>% visIgraphLayout(layout = "layout_with_fr") %>%
visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)
你可以相应地定制你自己的颜色。
编辑
对于您的注释,您输入了一个错误的名称(Xavier),您应该注意color
列的大小写。我们可以使用dplyr包中的merge()
或left_join
来合并基于列的数据帧。我将您的DF列名改为id
作为名称,以便它们可以匹配。
nodes <- data.frame(id = V(graph)$name, title = V(graph)$name)
nodes <- nodes[order(nodes$id, decreasing = F),]
colors = data.frame( "id" = c("John", "Peter", "Tim", "Kevin", "Adam", "Xavier", "Claude", "Henry"),
"color" = c("red", "blue", "green", "black", "red", "blue", "black", "blue") )
nodes <- merge(nodes, colors, by = "id")
edges <- get.data.frame(graph, what="edges")[1:2]
visNetwork(nodes, edges) %>% visIgraphLayout(layout = "layout_with_fr") %>%
visOptions(highlightNearest = TRUE, nodesIdSelection = TRUE)
https://stackoverflow.com/questions/64974727
复制相似问题