Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a force-directed graph in python?

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: force directed graph via R

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.

like image 226
ScottieB Avatar asked Aug 12 '16 23:08

ScottieB


1 Answers

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:

output of the graph described by OP

like image 195
Valentin Lorentz Avatar answered Sep 18 '22 23:09

Valentin Lorentz