networkx画图
使用networkx画图,关键是掌握draw_networkx_edges、draw_networkx_nodes和draw_networkx_labels三个方法的使用,设置好位置列表,节点列表,标签列表,理论上就可以绘制出任意的图了。详情参见:https://networkx.github.io,示例如下。
效果:
代码: options = { 'node_color': 'red', 'node_size': 300, 'with_labels': True, } G = createGraph(20, 5, 0.1) g, rings = getRelaxTree(G) # 画生成图 plt.sca(plt.subplot(121)) nx.draw_shell(G, **options) # 画松弛树 plt.sca(plt.subplot(122)) pos = nx.shell_layout(g) li = list(g.nodes) nx.draw_networkx_nodes(g, pos, nodelist=li) nx.draw_networkx_edges(g, pos) # 将R节点用不同颜色标记 R = [] for n in g.nodes: if 'isR' in G.nodes[n]: R.append(n) nx.draw_networkx_nodes(g, pos, nodelist=R, label='a', node_color='g', node_size=500) def getWeight(i): for e in g.edges: if e[1] == i: return (G.edges[e]['weight']) return 0 def getMiddlePos(e, p): x = np.array(p[e[0]]) y = np.array(p[e[1]]) z = (x + y) / 2 return tuple(z) # 绘制节点号 lables = {} for i in li: lables[i] = i nx.draw_networkx_labels(g, pos, lables) # 绘制各边权重 for i in li: # 修改标签为各边权重 lables[i] = getWeight(i) lables[0] = '' pos2 = {} for e in g.edges: pos2[e[1]] = getMiddlePos(e, pos) pos2[0] = (0, 0) nx.draw_networkx_labels(g, pos2, lables, font_color='b') plt.show()