python - 在 Python3 中绘制具有节点和边的网络

标签 python python-3.x algorithm prims-algorithm

我编写了一个算法来执行 dijkstra 算法。这是我在 A level 类(class)作业中制作的数学复习游戏。

我有这个数据:

Vertices: {'M', 'Y', 'X', 'C', 'F', 'Q'}
Edges: defaultdict(<class 'list'>, {'X': ['Y'], 'C': ['M'], 'M': ['C', 'F', 'Y'], 'Q': ['F'], 'Y': ['X', 'M'], 'F': ['M', 'Q']})
Weights: {('M', 'C'): 44, ('Q', 'F'): 27, ('Y', 'X'): 42, ('X', 'Y'): 42, ('Y', 'M'): 6, ('M', 'F'): 9, ('M', 'Y'): 6, ('F', 'Q'): 27, ('F', 'M'): 9, ('C', 'M'): 44} 

这些值是随机的,每次都不一样。

我可以使用什么来可视化网络以使其更清晰,例如节点(顶点)和弧(边)?或者有没有一种方法可以使用 print("o----o") 之类的打印语句将其可视化。

最佳答案

networkx 包的示例。我们将需要您提供的权重来构建图表。

import matplotlib.pyplot as plt
import networkx as nx
%matplotlib notebook    

Weights = {('M', 'C'): 44, ('Q', 'F'): 27, ('Y', 'X'): 42, ('X', 'Y'): 42, ('Y', 'M'): 6, ('M', 'F'): 9, ('M', 'Y'): 6, ('F', 'Q'): 27, ('F', 'M'): 9, ('C', 'M'): 44} 

G = nx.Graph()
# each edge is a tuple of the form (node1, node2, {'weight': weight})
edges = [(k[0], k[1], {'weight': v}) for k, v in Weights.items()]
G.add_edges_from(edges)

pos = nx.spring_layout(G) # positions for all nodes

# nodes
nx.draw_networkx_nodes(G,pos,node_size=700)

# labels
nx.draw_networkx_labels(G,pos,font_size=20,font_family='sans-serif')

# edges
nx.draw_networkx_edges(G,pos,edgelist=edges, width=6)

# weights
labels = nx.get_edge_attributes(G,'weight')
nx.draw_networkx_edge_labels(G,pos,edge_labels=labels)

布局

enter image description here

代码是从这个 Tutorial by Aric Hagberg 修改而来的和 answer by Marcus Müller .

关于python - 在 Python3 中绘制具有节点和边的网络,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48103119/

相关文章:

python - 您是否使用 get/set 模式(在 Python 中)?

Python 2.7 - 过滤目录内文件名中具有特定字符串的文件

python-3.x - 我应该使用 == 进行字符串比较吗?

algorithm - 这个函数的复杂度是多少?

algorithm - 以大 O 表示法 N 翻倍时的运行时间比率

python - 为什么 Matlab interp1 产生的结果与 numpy interp 不同?

python - 如何激活Python虚拟环境并同时执行脚本?

python-3.x - 如何修复 wxPython 模块中 wxPyDeprecationWarning 的警告?

java - 使用 arraylists 得到错误的输出

python - 如何使用 libsbml 读取 sbml 文件的属性