[英]Import graph from graphml restoring node positions with NetworkX
我正在以graphml格式保存带有节点位置的图形。
我想加载它并在与以前相同的位置绘制其节点。 保存在graphml文件中的数据由原始类型组成,而mathplotlib
用于绘制图形的数据是字典{string: array([x, y]), dtype=float32}
,其中array
很可能是numpy
数组。
我正在使用NetworkX 1.9.1,这是我的代码。 我猜问题可能是由于凌乱的迭代。 另外,我无法从头开始构建用于绘制位置的结构。
import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
#load the graph from the graphml file
def load_graph(file_path):
G = nx.read_graphml(file_path)
return G
def show_graph(G):
#used to create the structure, computation useless
pos = nx.circular_layout(G)
print(pos)
#try to refill the structure (don't produce expected results)
for (node, node_pos) in pos.items():
node_pos[0] = G.node[node]['x']
node_pos[1] = G.node[node]['y']
#draw the graph
print(pos)
plt.clf()
nx.draw_networkx(G, pos)
plt.show()
file_path = 'netw_a.graphml'
A = load_graph(file_path)
show_graph(A)
这是要导入的测试文件
<graphml xmlns="http://graphml.graphdrawing.org/xmlns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://graphml.graphdrawing.org/xmlns http://graphml.graphdrawing.org/xmlns/1.0/graphml.xsd">
<key attr.name="x" attr.type="double" for="node" id="d2" />
<key attr.name="y" attr.type="double" for="node" id="d1" />
<key attr.name="name" attr.type="string" for="graph" id="d0" />
<graph edgedefault="undirected">
<data key="d0">path_graph(4)</data>
<node id="0">
<data key="d1">0.394087123189</data>
<data key="d2">0.0</data>
</node>
<node id="1">
<data key="d1">0.743297296307</data>
<data key="d2">0.402465740641</data>
</node>
<node id="2">
<data key="d1">0.529781867707</data>
<data key="d2">0.942892202945</data>
</node>
<node id="3">
<data key="d1">0.0</data>
<data key="d2">1.0</data>
</node>
<edge source="0" target="1" />
<edge source="1" target="2" />
<edge source="2" target="3" />
</graph>
</graphml>
使用节点键将x和y值分配给字典
In [1]: pos = {}
In [2]: for n,data in G.node.items():
...: pos[n] = (data['x'],data['y'])
...:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.