briatte / ggnetwork

Geoms to plot networks with ggplot2
https://briatte.github.io/ggnetwork/
146 stars 28 forks source link

Position labels on curved edges in ggnetwork #28

Closed sciabolazza closed 5 years ago

sciabolazza commented 6 years ago

I am using the r package ggnetwork to plot a weighted directed graph.

My goal is to plot a label indicating the weight of each edge. Since the network is directed, I use the field curvature in the function geom_edges() to avoid overlapping edges. Then, I use the function geom_edgetext() to plot the weight of each edge.

My problem is that I do not know how to provide the new coordinates of the edges (after the curvature has been set) to geom_edgetext().

As a result, labels are positioned as if edges weren't curved. Any idea?

Following a reproducible example showing where I got so far:

# Load libraries
library(igraph); library(ggplot2); library(ggnetwork)

# Create adjacency matrix
m <- matrix(c(c(0,1,0,0,1,0,0),
           c(1,0,1,1,0,0,0),
           c(0,1,0,1,0,0,0),
           c(0,1,1,0,0,0,0),
           c(1,0,0,0,0,1,1),
           c(0,0,0,0,1,0,1),
           c(0,0,0,0,0,1,0)), nrow = 7, ncol = 7, byrow=T)

# Assign weights: column-normalize m
D <- diag(1/c(apply(m,2,sum)))
m <- m%*%D

# Create igraph object
g <- graph_from_adjacency_matrix(adjmatrix = m, mode = "directed", weighted = TRUE)

# Create ggnetwork object
n <- ggnetwork(g, layout = "fruchtermanreingold", cell.jitter = 0.25)

# Plot graph with weights
ggplot(n, aes(x = x, y = y, xend = xend, yend = yend)) +
geom_edges(size = 0.3, color = "grey50", arrow = arrow(length = unit(6,"pt")), curvature = 0.2) +
geom_nodes(size = 8, color = "orange") +
geom_edgetext(aes(label =  round(weight,2)), color = "grey25")+
theme_blank()+ theme(legend.position="none")
briatte commented 5 years ago

Dear @sciabolazza

Thanks for reporting this, and all apologies for not answering your issue earlier.

Unfortunately, I cannot easily solve that issue, and thus prefer referring to the ggraph package, which might well be able to do what you need. ggnetwork is simply not powerful/flexible enough for 'following' the edge curvature with your edge labels.