簡體   English   中英

使用NetworkX從graphml恢復節點位置導入圖形

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM