I want a graph that shows a few nodes, directional arrows between nodes representing a relationship, with thickness relative to the strength of their connection.
In R this is very simple
library("qgraph")
test_edges <- data.frame(
from = c('a', 'a', 'a', 'b', 'b'),
to = c('a', 'b', 'c', 'a', 'c'),
thickness = c(1,5,2,2,1))
qgraph(test_edges, esize=10, gray=TRUE)
Which produces:
But in Python I haven't been able to find a clear example. NetworkX and igraph seem to hint that it's possible, but I haven't been able to figure it out.
I first tried doing this with NetworkX's standard drawing functions, which use matplotlib, but I was not very successful.
However, NetworkX also supports drawing to the dot
format, which supports edge weight, as the penwidth
attribute.
So here is a solution:
import networkx as nx
G = nx.DiGraph()
edges = [
('a', 'a', 1),
('a', 'b', 5),
('a', 'c', 2),
('b', 'a', 2),
('b', 'c', 1),
]
for (u, v, w) in edges:
G.add_edge(u, v, penwidth=w)
nx.nx_pydot.write_dot(G, '/tmp/graph.dot')
Then, to show the graph, run in a terminal:
dot -Tpng /tmp/graph.dot > /tmp/graph.png
xdg-open /tmp/graph.png
(or the equivalent on your OS)
Which shows:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With