如何根据networkx python中的类别对网络图中的节点进行着色?

问题描述 投票:0回答:1

我正在尝试在相关数据上创建网络图,并希望根据类别为节点着色

数据样本视图: enter image description here

数据

import pandas as pd

links_data = pd.read_csv("https://raw.githubusercontent.com/johnsnow09/network_graph/refs/heads/main/links_filtered.csv")

图码:

import networkx as nx

G = nx.from_pandas_edgelist(links_data, 'var1', 'var2')
 
# Plot the network:
nx.draw(G, with_labels=True, node_color='orange', node_size=200, edge_color='black', linewidths=.5, font_size=2.5) 

enter image description here

该网络图中的所有节点都被着色为橙色,但我想根据 Category 变量对它们进行

着色。我寻找了更多示例,但不知道该怎么做。

如果需要,我也愿意使用其他 python 库。

感谢这里的任何帮助!

python networkx
1个回答
0
投票
由于 var1 和 Category 之间具有独特的关系,因此您可以使用以下方法为所有节点构建颜色列表:

import matplotlib as mpl cmap = mpl.colormaps['Set3'].colors # this has 12 colors for 11 categories colors = (links_data .melt(id_vars='Category', value_vars=['var1', 'var2'], value_name='node') .drop_duplicates('node').set_index('node')['Category'] .map(dict(zip(links_data['Category'].unique(), cmap))) .reindex(G.nodes) ) nx.draw(G, with_labels=True, node_color=colors, node_size=200, edge_color='black', linewidths=.5, font_size=2.5)
输出:

enter image description here

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.