7

Recently I discovered IPython notebook which is a powerful tool. As an IT student, I was looking for a way to represent graphs in Python. For example, I would like to know if there's a library (like numpy or matplotlib ?) which can draw from this

{ "1" : ["3", "2"],
  "2" : ["4"],
  "3" : ["6"],
  "4" : ["6"],
  "5" : ["7", "8"],
  "6" : [],
  "7" : [],
  "8" : []
}

something like this :

(source : developpez.com)

Is there something like this ?

WhatsThePoint
  • 3,395
  • 8
  • 31
  • 53
FunkySayu
  • 7,641
  • 10
  • 38
  • 61
  • Duplicate ? I'm testing : http://stackoverflow.com/questions/19472530/representing-graphs-data-structure-in-python – FunkySayu Apr 21 '15 at 13:58

3 Answers3

9

You can use networkx and, if you need to render the graph in ipython notebook, nxpd

import networkx as nx
from nxpd import draw
G = nx.DiGraph()
G.graph['dpi'] = 120
G.add_nodes_from(range(1,9))
G.add_edges_from([(1,2),(1,3),(2,4),(3,6),(4,5),(4,6),(5,7),(5,8)])
draw(G, show='ipynb')

enter image description here

AGS
  • 14,288
  • 5
  • 52
  • 67
  • Thank you, that was what i was looking for. I have just a little issue about valued graphs. Should i print the valuation manually or is there a parameter ? I looked for it but didn't found in the library `nxpd` – FunkySayu Apr 22 '15 at 16:56
  • `nxpd` can be installed with `pip install nxpd` – dominik andreas May 20 '17 at 11:08
6

You can use pygraphviz:

import pygraphviz

G = pygraphviz.AGraph(directed=True)
G.add_nodes_from(range(1,9))
G.add_edges_from([(1,2),(1,3),(2,4),(3,6),(4,5),(4,6),(5,7),(5,8)])
G.layout()
G.draw('graph.png')

Then in a markdown block:

![graph](graph.png)

Which renders to:

graph

Ryne Everett
  • 6,427
  • 3
  • 37
  • 49
1

There's already an answer using networkx and nxpd, however networkx on its own can plot directly via matplotlib (so you don't need nxpd):

import networkx as nx

%matplotlib inline

g = nx.DiGraph()
g.add_nodes_from(range(1, 9))
g.add_edges_from([(1, 2), (1, 3), (2, 4), (3, 6), (4, 5), (4, 6), (5, 7), (5, 8)])

nx.draw_planar(g, with_labels=True)

enter image description here

See the networkx documentation for more layout algorithms.

Florian Brucker
  • 9,621
  • 3
  • 48
  • 81
  • I tried the other answer but it seemed pip chose incompatible versions of the two packages. This answers saved me from figuring that out – Bananach Sep 26 '20 at 18:33