用Python3绘制具有节点和边的网络

2024-03-29 10:01:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我编写了一个算法来实现dijkstra的算法。这是一个数学复习游戏,我正在制作作为我的a水平课程的一部分。在

我有这个数据:

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")之类的打印语句来可视化它。在


Tags: 数据网络算法游戏可视化水平数学list
3条回答

看看networkxplot.ly、或{a3}。我不能推荐一些基于文本的ASCII艺术,比如可视化。使用一个精心设计的软件包可以给你更多的自由,也可以处理更复杂的数据,而可视化并不容易设置。在

一个带有networkx包的示例。我们需要您提供的Weights来构建图。在

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 Hagberganswer by Marcus Müller修改。在

您可以创建一个类Network,用顶点表示每条边,并为自定义可视化创建__repr__方法:

tree = {'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} 
class Vertex:
   def __init__(self, vertex, children):
      self.vertex = vertex
      self.children = children
   def __repr__(self):
      return '   '.join('{} -> {}:{}'.format(self.vertex, i, weights.get((self.vertex, i), weights.get((i, self.vertex), None))) for i in self.children)

class Network:
   def __init__(self, tree):
       self.__full_tree = [Vertex(*i) for i in tree.items()]
   def __repr__(self):
       return '\n'.join(repr(i) for i in self.__full_tree)

full_tree = Network(tree)
print(full_tree)

输出:

^{pr2}$

白色它远远不是教科书上的表现,它确实给出了基本思想。如果您正在寻找更专业的图表,请参阅下面@mattmilten的答案提供的链接。在

相关问题 更多 >