Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python NetworkX如何从文件中读取节点和边_Python_Matplotlib_Networkx - Fatal编程技术网

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

Python NetworkX如何从文件中读取节点和边,python,matplotlib,networkx,Python,Matplotlib,Networkx,我想读取带有节点和边的文件,以便传递以下信息: 每条边的重量 每个节点的Department_id如果Department_id>0,请使用特定颜色为节点着色,否则将其填充为黑色 以下是文件结构: graph [ node [ id 1 label "Node 1" department_id 1 ] node [ id 2 label "Node 2"

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

每条边的重量 每个节点的Department_id如果Department_id>0,请使用特定颜色为节点着色,否则将其填充为黑色 以下是文件结构:

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")
你能帮我读一下文件并做我描述的事情吗?
谢谢大家!

示例文件需要具有顶级graph[]声明才能成为有效的gml。例如

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()})

非常感谢。它工作得更好!我可以调整边缘权重宽度而不是边缘标签吗?例如,我尝试了:nx.draw_networkx_edgesself.G,pos,{frm,to:self.G.edge[frm][to][weight']for frm,to in-self.G.edges},width=float{frm,to:self.G.edge[frm][to][weight']for frm to,to in-in-self G.G.edges}但它无法解决它!nx.draw_networkx_edgeself.G,pos,width=[self.G.edge[frm][to][weight']对于frm,to in self.G.edges]