Networkx:如何在图形图中显示节点和边的属性 [英] Networkx: how to show node and edge attributes in a graph drawing

查看:1362
本文介绍了Networkx:如何在图形图中显示节点和边的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个图G,其节点和边的属性为状态".我想绘制图形,标记所有节点,并在相应的边/节点外部标记状态.

I have a graph G with attribute 'state' for nodes and edges. I want to draw the graph, all nodes labelled, and with the state marked outside the corresponding edge/node.

for v in G.nodes():     
    G.node[v]['state']='X'
G.node[1]['state']='Y' 
G.node[2]['state']='Y'

for n in G.edges_iter():    
    G.edge[n[0]][n[1]]['state']='X'
G.edge[2][3]['state']='Y'

命令draw.networkx具有标签选项,但是我不明白如何为该命令提供属性作为标签.有人可以帮我吗?

The command draw.networkx has an option for labels, but I do not understand how to provide the attribute as a label to this command. Could someone help me out?

推荐答案

虽然不是很漂亮-但它的工作方式如下:

It's not so pretty - but it works like this:

from matplotlib import pyplot as plt
import networkx as nx
G = nx.Graph()
G.add_edge(1,2)
G.add_edge(2,3)
for v in G.nodes():
    G.node[v]['state']='X'
G.node[1]['state']='Y'
G.node[2]['state']='Y'

for n in G.edges_iter():
    G.edge[n[0]][n[1]]['state']='X'
G.edge[2][3]['state']='Y'

pos = nx.spring_layout(G)

nx.draw(G, pos)
node_labels = nx.get_node_attributes(G,'state')
nx.draw_networkx_labels(G, pos, labels = node_labels)
edge_labels = nx.get_edge_attributes(G,'state')
nx.draw_networkx_edge_labels(G, pos, labels = edge_labels)
plt.savefig('this.png')
plt.show()

这篇关于Networkx:如何在图形图中显示节点和边的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆