通过属性绘制节点形状和节点颜色

jan*_*ins 1 python matplotlib networkx

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

>>> 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']
{}
Run Code Online (Sandbox Code Playgroud)

然后我使用绘制图

>>> nx.draw(G,with_labels = True)
>>> plt.show()
Run Code Online (Sandbox Code Playgroud)

现在我得到带有红色圆圈的图形。对于我图中未定义的所有内容,如何获得ART1红色正方形的蓝色圆柱体和DOC紫色紫色的圆柱体?

Bon*_*fum 5

有多种方法可以根据节点的属性选择节点。这是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')
Run Code Online (Sandbox Code Playgroud)

  • 我忘了提到我在 python3.6 中工作:对于每个在这个解决方案上遇到问题的人。使用 `items()` 而不是 `iteritems()` - `nx.get_node_attributes(G,'Type').items()` (3认同)