我目前有一个形式为(node1、node2、weight_of_edge)的三元组列表。我有什么方法可以绘制,以便它们之间有边缘的节点在布局中保持靠近?
问问题
786 次
1 回答
1
您应该看看NetworkX库,它提供了许多用于创建和操作网络的工具。
基于三元组列表的基本示例:
list_of_triplets = [("n1", "n2", 4),
("n3", "n4", 1),
("n5", "n6", 2),
("n7", "n8", 4),
("n1", "n7", 4),
("n2", "n8", 4),
("n8", "n9", 6),
("n4", "n9", 12),
("n4", "n6", 1),
("n2", "n7", 4),
("n1", "n8", 4)]
# The line below in the code change the list in a format that take
# a weight argument in a dictionary, to be computed by NetworkX
formatted_list = [(node[0], node[1], {"weight":node[2]}) for node in list_of_triplets]
要绘制图形:
import matplotlib.pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_edges_from(formatted_list)
nx.draw(G)
plt.show()
于 2013-02-25T16:28:01.987 回答