这似乎应该是一种相当可视化的技术,但我想不出一种好方法。
假设我有以下图表:
G = make_undirected_graph(c(1,2,
2,3,
3,4))
V(G)$attribute = c(T,T,T,F)
我想根据两个顶点的attribute
值是否相同,绘制边缘颜色不同的图。
当我尝试学习igraph
时,看起来如此简单的任务使我发疯。我发现现在使用tidygraph
更容易,它使用tidyverse
动词来操纵igraph
对象。它带有由同一个人开发并遵循ggplot2
(图形语法)实现的逻辑的用于绘图的配套程序包。
library(ggraph)
library(tidygraph)
G %>%
as_tbl_graph() %>%
activate(edges) %>% # this determines if edges or nodes are manipulated
mutate(agreement = .N()$attribute[from] == .N()$attribute[to]) %>% # .N() makes the node data available while manipulating edges
ggraph() + # using ggraph to plot
geom_node_point() +
geom_edge_link(aes(colour = agreement)) +
theme_graph()
您还可以混合和匹配igraph
和tidygraph
/ ggraph
,因为tidygraph
对象仍然是有效的igraph
对象。
个人,我喜欢tidygraph
/ ggraph
解决方案,但是如果您有兴趣,可以在igraph
中执行此操作。
library(igraph)
G = make_undirected_graph(c(1,2,
2,3,
3,4))
V(G)$attribute = c(T,T,T,F)
# Get the index for nodes with the attribute
idx <- which(V(G)$attribute)
# Assign the "non-homophilous" color
E(G)$color <- "tomato"
# Assign the "homophilous" color using the index and the `%--%` operator
E(G)[idx %--% idx]$color <- "steelblue"
plot(G)
由reprex package(v0.3.0)在2020-03-23创建
这可以概括为具有任意数量特征的属性:
G <- igraph::sample_gnp(150, 0.05)
V(G)$gender <- sample(c("M", "F", "NB"), 150, replace = TRUE)
m_idx <- which(V(G)$gender == "M")
f_idx <- which(V(G)$gender == "F")
nb_idx <- which(V(G)$gender == "NB")
E(G)$color <- "tomato"
E(G)[m_idx %--% m_idx]$color <- "steelblue"
E(G)[f_idx %--% f_idx]$color <- "steelblue"
E(G)[nb_idx %--% nb_idx]$color <- "steelblue"
plot(G, vertex.size = 5, vertex.label = NA)
由reprex package(v0.3.0)在2020-03-23创建