Skip to main content
 首页 » 编程设计

python之使用networkx按属性绘制节点形状和节点颜色

2025年05月04日23jpfss

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

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

之后我使用

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

现在我得到一个带有红色圆圈的图表。我怎样才能得到例如 ART 的蓝色循环 DOC 的红色方 block 一切未定义的紫色循环 在我的阴谋中?

请您参考如下方法:

有多种方法可以根据属性选择节点。以下是如何使用 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')