我刚刚执行了一个代码来使用 igraph 和 tidygraph 获得一致的图形。在我的示例中,A 和 C 之间的权重仅为 1。因此 igraph 包中的网络图将权重适当地反映为距离。
但是,我认为 tidygraph 未能将重量作为距离。例如,尽管权重很大,但 B 和 E 没有联系。
如何将重量反映为距离?
source target weight
1 A B 4
2 A B 7
3 A C 1
4 A D 2
5 A J 11
6 J A 14
7 B E 18
8 B F 19
9 C G 1
10 C H 10
11 D I 14
12 I I 10
# https://www.r-graph-gallery.com/249-igraph-network-map-a-color.html
# library
library(igraph)
set.seed(1)
# Create data
links <- data.frame(
source = c("A","A", "A", "A", "A","J", "B", "B", "C", "C", "D","I"),
target = c("B","B", "C", "D", "J","A","E", "F", "G", "H", "I","I"),
weight = sample(1:20, 12, replace = T)
)
# Print out weights
links$weight
nodes <- data.frame(
name=LETTERS[1:10],
carac = c(rep("young", 3), rep("adult", 2), rep("old", 5))
)
# Turn it into igraph object
network <- graph_from_data_frame(d = links, vertices = nodes, directed = F)
# Make a palette of 3 colors
library(RColorBrewer)
coul <- brewer.pal(3, "Set1")
# Create a vector of color
my_color <- coul[as.numeric(as.factor(V(network)$carac))]
# Make the plot
plot(network, vertex.color = my_color)
# See colors
as.factor(nodes$carac)
library(ggraph)
library(tidygraph)
#
g <- tbl_graph(nodes, links, directed = FALSE)
g %>% mutate(degree = centrality_degree(),
community = carac)%>%
ggraph(layout = "lgl") +
geom_edge_link(aes(width = 1),
alpha = 0.8,
colour = "lightgray") +
scale_edge_width(range = c(0.1, 1)) +geom_node_point(aes(colour = community, size = degree)) +
geom_node_text(aes(label = name), repel = TRUE) +
theme_graph()