如何根据igraph中的边是否相同来着色图的边缘?

问题描述 投票:0回答:2

这似乎应该是一种相当可视化的技术,但我想不出一种好方法。

假设我有以下图表:

G = make_undirected_graph(c(1,2,
                            2,3,
                            3,4))

V(G)$attribute = c(T,T,T,F)

我想根据两个顶点的attribute值是否相同,绘制边缘颜色不同的图。

r igraph
2个回答
2
投票

当我尝试学习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()

“”

您还可以混合和匹配igraphtidygraph / ggraph,因为tidygraph对象仍然是有效的igraph对象。


1
投票

个人,我喜欢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创建

© www.soinside.com 2019 - 2024. All rights reserved.