按属性

时间:2018-03-22 12:21:38

标签: python matplotlib networkx

在图表G中,我有一组节点。其中一些属性Type可以是MASTERDOC。其他人没有类型定义:

>>> import networkx as nx
>>> import matplotlib.pyplot as plt
>>> G=nx.Graph()
[...]
>>> G.node['ART1']
{'Type': 'MASTER'}
>>> G.node['ZG1']
{'Type': 'MASTER'}
>>> G.node['MG1']
{}

然后我使用

绘制图表
>>> nx.draw(G,with_labels = True)
>>> plt.show()

现在我得到一个带有红色圆圈的图表。我怎样才能得到 ART1的蓝色圆柱 DOC的红色正方形 紫色圆筒,一切都未定义 在我的情节?

1 个答案:

答案 0 :(得分:3)

有多种方法可以根据属性选择节点。以下是如何使用get_node_attributes和列表理解来获取子集。然后绘图函数接受nodelist参数。

根据这种方法,应该很容易扩展到更广泛的条件或修改每个子集的外观以满足您的需求

import networkx as nx

# define a graph, some nodes with a "Type" attribute, some without.
G = nx.Graph()
G.add_nodes_from([1,2,3], Type='MASTER')
G.add_nodes_from([4,5], Type='DOC')
G.add_nodes_from([6])


# extract nodes with specific setting of the attribute
master_nodes = [n for (n,ty) in \
    nx.get_node_attributes(G,'Type').iteritems() if ty == 'MASTER']
doc_nodes = [n for (n,ty) in \
    nx.get_node_attributes(G,'Type').iteritems() if ty == 'DOC']
# and find all the remaining nodes.
other_nodes = list(set(G.nodes()) - set(master_nodes) - set(doc_nodes))

# now draw them in subsets  using the `nodelist` arg
pos = nx.spring_layout(G)
nx.draw_networkx_nodes(G, pos, nodelist=master_nodes, \
    node_color='red', node_shape='o')
nx.draw_networkx_nodes(G, pos, nodelist=doc_nodes, \
    node_color='blue', node_shape='o')
nx.draw_networkx_nodes(G, pos, nodelist=other_nodes, \
    node_color='purple', node_shape='s')