NetworkX如何从文件中读取节点和边缘

时间:2015-01-16 18:55:31

标签: python matplotlib networkx

我想读取带有节点和边的文件,以便传递以下信息:

  1. 每条边的重量
  2. 每个节点的Department_id(如果department_id> 0,使用特定颜色为节点着色,否则将其填充为黑色)
  3. 这是文件结构:

    graph [      
          node [
            id 1
            label "Node 1"
            department_id 1
          ]
          node [
            id 2
            label "Node 2"
            department_id 0
          ]
          node [
            id 3
            label "Node 3"
            department_id 2
          ]
          edge [
            source 1
            target 2
            weight 7
          ]
          edge [
            source 1
            target 3
            weight 3
          ]
          edge [
            source 2
            target 3
            weight 1
          ]
    ]
    

    这是我阅读文件和绘制网络的简单代码:

    def gml_file_importer(self):
            self.G = nx.read_gml(self.gml_file)
            print "GML file %s was successfully imported" %self.gml_file
    
    def draw_network(self):
            nx.draw(self.G, node_size=30)
            plt.savefig("graph")
    

    你能帮助我一点点阅读文件,做我描述的吗? 谢谢!

1 个答案:

答案 0 :(得分:0)

您的示例文件需要具有顶级" graph []"声明是有效的gml。 E.g。

graph [
  node [
    id 1
    label "Node 1"
    dapartment id 1
  ]
  ...
]

一旦我添加该文件导入networkx就好了。

这将绘制图形G,将节点着色为绿色或黑色并添加标签。

pos = nx.circular_layout(G)
nx.draw_networkx_nodes(G, pos, 
  nodelist=[n for n in G.node if G.node[n]['department_id'] > 0], node_color='g')
nx.draw_networkx_nodes(G, pos, 
  nodelist=[n for n in G.node if G.node[n]['department_id'] <= 0], node_color='black')
nx.draw_networkx_edges(G, pos)
nx.draw_networkx_edge_labels(G, pos, 
  {(frm, to): G.edge[frm][to]['weight'] for (frm, to) in G.edges()})