FunkySayu
FunkySayu

Reputation: 8061

How to represent graphs with IPython

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 ?

Upvotes: 7

Views: 5924

Answers (4)

Amnon
Amnon

Reputation: 2888

import graphviz

source = '''
digraph structs { 
  1 -> 3;
  1 -> 2;
  2 -> 4;
  3 -> 6;
  4 -> 6;
  4 -> 5;  
  5 -> 7;
  5 -> 8;
}
'''

dot = graphviz.Source(source6)

# Render the Graph
dot

Upvotes: 0

Florian Brucker
Florian Brucker

Reputation: 10355

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.

Upvotes: 1

Ryne Everett
Ryne Everett

Reputation: 6819

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

Upvotes: 6

AGS
AGS

Reputation: 14498

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

Upvotes: 9

Related Questions