1.有向图
#-*- 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])
nx.add_cycle(G,[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()
image.png
2.无向图
#-*- 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])
nx.add_cycle(G,[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()
image.png
3.节点颜色图
#-*- coding:utf8-*-
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,3,4,5,6]
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()
image.png
计算:
计算1:求无向图的任意两点间的最短路径
#-*- coding:utf8-*-
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)])
path = nx.all_pairs_shortest_path(G)
print (list(path)[0]) # 1 到各个几点的最短路径。(list(path)[1]) 2到各个节点的最短路劲
结果
PS D:\project\pyscripts\graph> python .\gg.py
(1, {1: [1], 2: [1, 2], 3: [1, 3], 4: [1, 4], 5: [1, 5], 6: [1, 4, 6]})
计算2:求出有向图中得环
#-*- coding:utf8-*-
#-*- coding:utf8-*-
import networkx as nx
import matplotlib.pyplot as plt
G = nx.DiGraph()
G.add_edges_from([(1,2),(2,3),(3,2),(3,4),(4,2),(2,5),(5,6),(5,'a'),('a','b'),('b',5)])
path = nx.simple_cycles(G) #找出有向环
print(list(path))
nx.draw_networkx(G,pos=nx.spring_layout(G))
plt.show()
结果:
PS D:\project\pyscripts\graph> python .\gg.py
[[2, 3, 4], [2, 3], ['b', 5, 'a']]
image.png
网友评论