thomasp85 / ggraph

Grammar of Graph Graphics
https://ggraph.data-imaginist.com
Other
1.08k stars 116 forks source link

plot behaviour of factors with geom_edge_link() #278

Closed jlguilherme closed 3 years ago

jlguilherme commented 3 years ago

Hi - great package! Thanks!

I'm having an issue with the order edges are plotted with geom_edge_link() - I need them to respect the order of factor levels (factor cat below) and to have different widths according to value in strength.

I would expect edges to be plotted in "order" they appear in the edge list that feeds tbl_graph but that does not seem to be the case - what should be the expected behaviour?

Consider the following dataframe
from <- c("A","A","A","A","A","B","B","B","B","B","C","C","D","D","D","D","D","D","D","D","E","E","E","E","E","F","F","G","G","G","G","G","G")
to <- c("H","I","I","J","O","O","H","I","I","N","N","H","N","J","H","J","J","I","I","J","L","N","J","L","H","L","H","M","J","N","I","H","H")
cat <- c("weak","moderate","strong","v_strong","weak","moderate","strong","v_strong","weak","moderate","strong","v_strong","weak","weak","weak","weak","weak","weak","moderate","strong","v_strong","moderate","moderate","moderate","moderate","strong","v_strong","weak","weak","weak","weak","strong","v_strong")
strength <- c(0.7,1,0.4,0.9,0,0,0.2,0.4,0.2,0.6,0.5,0.3,1,0.5,0.6,0.2,0.5,0.7,1,0,0.2,0.8,0.5,0.4,0.1,0,0.7,0.2,0.5,0.7,0.3,0.4,0.6)

df <- data.frame(from, to, cat, strength)
Order the level in factor 'cat'
df$cat <- factor(df$cat, levels = c("weak", "moderate", "strong", "v_strong"))

levels(df$cat)

[1] "weak"     "moderate" "strong"   "v_strong"

edge list

edge.list <- df

node list

n.from <- df %>%
   group_by(from) %>%
   summarise(n = n()) %>%
   rename(name = from)

n.to <- df %>%
  group_by(to) %>%
  summarise(n = n()) %>%
  rename(name = to)

node.list <- rbind(n.from, n.to)

tbl_graph file

Netw <- tbl_graph(nodes = node.list, edges = edge.list)

plot it!

ggraph(Netw) +
 geom_edge_link(aes(edge_colour = cat, width = strength)) +
 scale_edge_width_continuous(limits = c(0,1), range=c(.1,2.5)) +
 scale_edge_colour_manual(values = c("moderate" = "grey80", "weak" = "red", "very strong" = "#3E1404", "strong" = "#9F6B39"))

I get this:

Rplot01

However, I would expect the red edges (i.e. level "weak") to be in the 'back' and over all the other edges.

I tried different things but just don't understand if this is the expected behaviour and how I can obtain my desired output.

Thanks for your help!

jlguilherme commented 3 years ago

same