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

时间:2020-03-23 16:27:18

标签: r igraph

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

假设我有以下图表:

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

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

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

2 个答案:

答案 0 :(得分: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对象:

G2 <- G %>% 
  as_tbl_graph() %>% 
  activate(edges) %>% # this determines if edges or nodes are manipulated
  mutate(agreement = .N()$attribute[from] == .N()$attribute[to]) %>% 
  mutate(color = ifelse(agreement, "green", "red"))
plot(G2)

答案 1 :(得分:2)

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

library(dplyr)
library(igraph)

G <- sample_gnp(150, 0.05)

V(G)$quant <- runif(150)

epsilon <- 0.5

G <- G %>% 
  igraph::as_data_frame() %>% 
  mutate(diff = abs(V(G)$quant[.[,1]] - V(G)$quant[.[,2]]) > epsilon) %>% 
  graph_from_data_frame(directed = FALSE)

E(G)$color <- ifelse(E(G)$diff, "steelblue", "tomato")

plot(G, vertex.size = 5, vertex.label = NA, color = diff)

reprex package(v0.3.0)于2020-03-24创建