问题
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 :
Is there something like this ?
回答1:
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')
回答2:
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:

Which renders to:
回答3:
If you also want to animate the graphs (for instance, to explore how an algorithm works) you can use https://github.com/mapio/GraphvizAnim
来源:https://stackoverflow.com/questions/29774105/how-to-represent-graphs-with-ipython