Как вы окрашиваете края графа в зависимости от того, являются ли они гомофильными в igraph? - PullRequest
1 голос
/ 23 марта 2020

Такое ощущение, что это должен быть довольно метод визуализации, но я не могу найти хороший способ сделать это.

Допустим, у меня есть следующий график:

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

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

Я хочу создать график с разным цветом кромки в зависимости от того, имеют ли две вершины одинаковое значение для attribute.

Ответы [ 2 ]

2 голосов
/ 23 марта 2020

Лично мне нравится решение 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)

Создано в 2020-03-23 ​​пакетом представ. (v0.3.0)

Это может быть обобщено для атрибутов с произвольным числом признаков:

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)

Создано в 2020-03-23 ​​с помощью представительного пакета (v0.3.0)

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)

Создано в 2020-03-24 с помощью пакета представить (v0.3.0)

2 голосов
/ 23 марта 2020

Казалось бы, простые задачи, подобные этой, сводили меня с ума, когда я пытался выучить igraph. Сейчас мне гораздо проще работать с tidygraph, который использует tidyverse глаголы для манипулирования igraph объектами. Он поставляется с сопутствующим пакетом для черчения, разработанным теми же людьми и следуя логике c, реализованной 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 объекты:

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)

...