Kayla
Kayla

Reputation: 31

Add color to edge using igraph in R

I'm trying to get the links to each node to have the same color as the node itself. However, I've not been able to find any way to accomplish this while still keeping the amount of connections visible.

The code and the output:

library(igraph)

net <- graph_from_data_frame(d = send_rec, directed = TRUE, vertices = NULL)

colrs <- c("deepskyblue1","firebrick2","chartreuse1","yellow1","chocolate1","blueviolet")

plot(net, layout=layout.circle, vertex.color= colrs, main="circle")

network analysis

Ideally the gray lines would become the color of the node they are coming from while not just becoming one solid line.

Thanks in advance!

Upvotes: 2

Views: 266

Answers (1)

Allan Cameron
Allan Cameron

Reputation: 174478

You will get much nicer plotting results with a wider range of customization options if you use the ggraph package.

Obviously, we don't have your data, but using a similar graph from made-up data (see below), we can do:

library(igraph)
library(ggraph)
library(tidygraph)

net <- graph_from_data_frame(d = send_rec, directed = TRUE, vertices = NULL)

colrs <- c("deepskyblue1","firebrick2","chartreuse1",
           "yellow1","chocolate1","blueviolet")

as_tbl_graph(net) %>% 
  activate(edges) %>% 
  mutate(to_name = .N()$name[to], 
         from_name = .N()$name[from]) %>%
  ggraph(layout = "linear", circular = TRUE)  +
  geom_edge_fan(aes(color = from_name), alpha = 0.3) +
  geom_node_circle(aes(fill = name, r = 0.2)) +
  geom_node_text(aes(label = name), fontface = "bold") +
  scale_fill_manual(values = colrs, guide = "none") +
  scale_edge_color_manual(values = colrs, guide = "none") +
  theme_graph() +
  coord_equal()

enter image description here

Created on 2022-10-26 with reprex v2.0.2


Reproducible example data

set.seed(1)

dept <- c("Admin", "Engineering", "IT", "Marketing", "Operations", "Sales")

send_rec <- data.frame(from = factor(sample(dept, 400, TRUE)), 
                       to   = factor(sample(dept, 400, TRUE)))

send_rec <- send_rec[send_rec$from != send_rec$to,]

Upvotes: 1

Related Questions