環境:win7(AMD32bit) + python2.6 + network1.8.1
html
依賴:node
numpy https://pypi.python.org/packages/2.6/n/numpy/numpy-1.6.1.win32-py2.6.exe#md5=67e0c10cf55b713bd27cbba94dee9673python
pyparsing http://ncu.dl.sourceforge.net/project/pyparsing/pyparsing/pyparsing-2.0.1/pyparsing-2.0.1.win32-py2.6.exespring
datautil https://pypi.python.org/packages/source/p/python-dateutil/python-dateutil-2.2.tar.gz#md5=c1f654d0ff7e33999380a8ba9783fd5capp
matplotlib http://ncu.dl.sourceforge.net/project/matplotlib/matplotlib/matplotlib-1.3.1/matplotlib-1.3.1.win32-py2.6.exe工具
networkx https://pypi.python.org/packages/source/n/networkx/networkx-1.8.1.zip#md5=4a90328898d9db29bbb12ef3e6223bab.net
six https://pypi.python.org/packages/source/s/six/six-1.5.2.tar.gz#md5=322b86d0c50a7d165c05600154cecc0acode
安裝:bulabula...
htm
源碼:blog
有向圖
#-*- coding:utf8-*- import networkx as nx import matplotlib.pyplot as plt G = nx.DiGraph() G.add_node(1) G.add_node(2) G.add_nodes_from([3,4,5,6]) G.add_cycle([1,2,3,4]) G.add_edge(1,3) G.add_edges_from([(3,5),(3,6),(6,7)]) nx.draw(G) plt.savefig("youxiangtu.png") plt.show()
8節點徹底圖
import networkx as nx import matplotlib.pyplot as plt G = nx.complete_graph(8) nx.draw(G) plt.savefig("8nodes.png") plt.show()
無向圖
#-*- coding:utf8-*- import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() G.add_node(1) G.add_node(2) G.add_nodes_from([3,4,5,6]) G.add_cycle([1,2,3,4]) G.add_edge(1,3) G.add_edges_from([(3,5),(3,6),(6,7)]) nx.draw(G) plt.savefig("wuxiangtu.png") plt.show()
顏色節點圖
import networkx as nx import matplotlib.pyplot as plt G = nx.Graph() G.add_edges_from([(1,2),(1,3),(1,4),(1,5),(4,5),(4,6),(5,6)]) pos = nx.spring_layout(G) colors = [1,2,2,2,3,1] nx.draw_networkx_nodes(G,pos,node_color=colors) nx.draw_networkx_edges(G,pos) plt.axis('off') plt.savefig("color_nodes.png") plt.show()
效果:
計算:
import networkx as nx import matplotlib.pyplot as plt #計算1:求無向圖的任意兩點間的最短路徑 G = nx.Graph() G.add_edges_from([(1,2),(1,3),(1,4),(1,5),(4,5),(4,6),(5,6)]) path = nx.all_pairs_shortest_path(G) print path[1] #計算2:求出圖中在環上的點 G = nx.Graph() G.add_edges_from([(1,2),(1,3),(1,4),(1,5),(4,5),(4,6),(5,6)]) path = nx.all_pairs_shortest_path(G) print path[1]
輸出:
{1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 4], 5: [1, 5], 6: [1, 4, 6]}
{1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 4], 5: [1, 5], 6: [1, 4, 6]}
不錯的帖子:http://blog.sina.com.cn/s/blog_720448d301018px7.html