Map directed edge attribute to scale_edge_color_gradient aes in ggraph

542 views Asked by At

I'm learning to use tidygraph and ggraph to plot social network data. I like it so far, but I can't figure out how to use color gradients to indicate edge direction while also mapping the color (that the gradient is based on) to an edge attribute.

Example data

require(tidygraph)
require(ggraph)

edges_df <- tibble(from = c("A","A","B","C","C","D"),
                   to = c("C","B","D","B","D","A"),
                   edgewidth = c(1,3,3,2,4,1),
                   edgegradient = factor(c("red","blue","red","blue","blue","red"))) 
# I realize edge gradient could be any attribute, not necessarily the names of the desired colors.

nodes_df <- tibble(node_id = c("A","B","C","D"))

my_graph <- tbl_graph(directed = TRUE, nodes = nodes_df, edges = edges_df)

ggraph(my_graph %>%
         activate(edges), layout = "linear", circular = TRUE) +
  geom_edge_arc(aes(width = edgewidth, color = stat(..index..))) +
  geom_node_label(aes(label = node_id), size = 10)

Here is the ggraph plot (since I'm new to SO, I can't embed the image).

What I want: Edges A->C, D->A, and B->D to be a red gradient, and edges A->B, C->B, and C->D to be a blue gradient. I have a feeling I'm confusing what geom_edge_arc's color aesthetic is doing versus what the scale_edge_color_* aesthetic does.

I like that ggraph uses the ggplot engine and similar syntax, so if at all possible, an answer using ggraph would be great. If not, that's okay.

1

There are 1 answers

1
stefan On

Maybe this what you are looking for. There is probably a solution to achieve via a well-specified color gradient. However, after habing a look at the issue a simple solution to get two different "color gradients" is to map ..index.. on the alpha aesthetic, while mapping edgegradient on color. To get the right colors you could make use scale_edge_color_identity:

library(tidygraph)
library(ggraph)
library(tibble)

edges_df <- tibble(from = c("A","A","B","C","C","D"),
                   to = c("C","B","D","B","D","A"),
                   edgewidth = c(1,3,3,2,4,1),
                   edgegradient = factor(c("red","blue","red","blue","blue","red"))) 
# I realize edge gradient could be any attribute, not necessarily the names of the desired colors.

nodes_df <- tibble(node_id = c("A","B","C","D"))

my_graph <- tbl_graph(directed = TRUE, nodes = nodes_df, edges = edges_df)

ggraph(my_graph %>%
         activate(edges), layout = "linear", circular = TRUE) +
  geom_edge_arc(aes(width = edgewidth, alpha = stat(..index..), color = edgegradient)) +
  geom_node_label(aes(label = node_id), size = 10) +
  scale_edge_color_identity(guide = "legend")

enter image description here