我有一个包含此类数据的文件
497014;5674;200
5674;5831;400
410912;5674;68.5
7481;5674;150
5831;5674;200
5831;5674;300
前两个元素是节点,而第三个是标签(特定于节点之间特定关系的参数)。您可以使用此代码绘制数据(python 3.4,networkx 1.9)(感谢@mdml)
import networkx as nx
import matplotlib.pyplot as plt
data= open("C:\\Users\\User\\Desktop\\test-py.csv", "r")
G = nx.MultiDiGraph()
edge_labels = dict()
for line in data:
node1, node2, weight1 = (line.strip()).split(";")
length = float(weight1)
G.add_edge(node1, node2, label=str(weight1), length=length)
edge_labels[(node1, node2)] = weight1 # store the string version as a label
# Draw the graph
pos = nx.spring_layout(G) # set the positions of the nodes/edges/labels
nx.draw_networkx(G, pos=pos) # draw everything but the edge labels
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels, label_pos=0.3)
# label_pos needed to not overwrite when you have two labels
plt.show()
但是如何在两个节点之间绘制三个(或更多)标记边(例如,在节点5831和5674之间)?
感谢。
#我修改了以前的代码,为记录添加了一个唯一的密钥,用于多种图形:
import networkx as nx
import matplotlib.pyplot as plt
data= open("C:\\Users\\User\\Desktop\\test-py.csv", "r")
G = nx.MultiDiGraph() #for the example below Undirected I used the MultiGraph() version
edge_labels = dict()
k=0 # added
for line in data:
node1, node2, weight1 = (line.strip()).split(";")
length = float(weight1)
G.add_edge(node1, node2, key=str(k), label=str(weight1), length=length)
# modified with key
edge_labels[(node1, node2)] = weight1
k+=1 # added
# Draw the graph
pos = nx.spring_layout(G)
nx.draw_networkx(G, pos=pos)
nx.draw_networkx_edge_labels(G, pos=pos, edge_labels=edge_labels, label_pos=0.3)
plt.show()
可以查询数据以提取信息。 例如,在节点5674和5831之间:
定向(使用MultiDiGraph())
>>> G.get_edge_data('5674', '5831')
{'1': {'length': 400.0, 'label': '400'}}
>>> G.get_edge_data('5831','5674')
{'5': {'length': 300.0, 'label': '300'}, '4': {'length': 200.0, 'label': '200'}}
无向(使用MultiGraph())
>>> G.get_edge_data('5674', '5831')
{'5': {'length': 300.0, 'label': '300'}, '4': {'length': 200.0, 'label': '200'}, '1': {'length': 400.0, 'label': '400'}}
但是图形与以前相同:节点之间只有一个连接。 我想利用可视化的力量在更短的时间内获得更多(高级别)信息。出于这个原因,我对“如何绘制/绘制这些数据感兴趣?”感兴趣。 我会继续测试。
再次感谢。