Search code examples
rggraph

Legend line thickness in ggraph


When using ggraph, is there a way to thicken the legend lines for edge color? I'm trying to override but to no avail. Here's an example:

library(tidyverse)
library(igraph)
library(ggraph)

set.seed(20190607)

#create dummy data
Nodes <- tibble(source = sample(letters, 8))
Edges <- Nodes %>% 
  mutate(target = source) %>% 
  expand.grid() %>% 
  #assign a random weight & color
  mutate(weight = runif(nrow(.)),
         color = sample(LETTERS[1:5], nrow(.), replace = TRUE)) %>% 
  #limit to a subset of all combinations
  filter(target != source,
         weight > 0.7)


#make the plot
Edges %>% 
  graph_from_data_frame(vertices = Nodes) %>% 
  ggraph(layout = "kk") + 
  #link width and color are dynamic
  geom_edge_link(alpha = 0.5, aes(width = weight, color = color)) + 
  geom_node_point(size = 10) + 
  theme_graph() + 
  #don't need a legend for edge width, but the color override doesn't work
  guides(edge_width = FALSE,
         edge_color = guide_legend(override.aes = list(size = 2))) 

Can barely see the legend lines

My preferred output would look more like this:

enter image description here


Solution

  • I think you really want to adjust the width aesthetic and not size, so that's one little fix.

    But the tricky part (at least for me) is because ggraph is expanding the aesthetic names automatically, e.g. width >>> edge_width, so you need to use the edge_x format when trying to override the aesthetics in guide_legend().

    So you end up with something like this:

    Edges %>% 
      graph_from_data_frame(vertices = Nodes) %>% 
      ggraph(layout = "kk") + 
      geom_edge_link(alpha = 0.5, aes(width = weight, edge_color = color)) + 
      geom_node_point(size = 10) + 
      theme_graph() + 
      guides(edge_color = guide_legend(override.aes = list(edge_width = 5)),
             edge_width = F) 
    

    enter image description here