主要问题是将属性 DataFrame 变成更有用的东西。我们可以通过set_index到Node创建一个Node到color的映射,map将当前属性数值转换成color:
import networkx as nx
import pandas as pd
edges_df = pd.DataFrame({
'Node': ['A', 'A', 'B', 'B', 'B', 'S'],
'Edge': ['B', 'D', 'N', 'A', 'X', 'C']
})
# Abridged but contains values for all nodes in `edges_df`
attributes_df = pd.DataFrame({
'Node': ['A', 'B', 'C', 'D', 'N', 'S', 'X'],
'Attribute': [-1, 0, -1.5, 1, 1, 1.5, 0]
})
mapper = {-1.5: 'grey', -1: 'red', 0: 'orange', 1: 'yellow', 1.5: 'green'}
colour_map = attributes_df.set_index('Node')['Attribute'].map(mapper)
colour_map:
Node
A red
B orange
C grey
D yellow
N yellow
S green
X orange
Name: Attribute, dtype: object
*注意:在上述属性数据集中,值1.5 和节点S 都没有表示,因此所有节点都带有颜色,并且所有颜色都表示S 在attributes_df 中设置为1.5
colour_map 然后可以用于set_node_attributes:
G = nx.from_pandas_edgelist(edges_df, source='Node', target='Edge')
# Add Attribute to each node
nx.set_node_attributes(G, colour_map, name="colour")
# Then draw with colours based on attribute values:
nx.draw(G,
node_color=nx.get_node_attributes(G, 'colour').values(),
with_labels=True)
或者我们可以通过reindexing 基于图形节点直接使用系列(不创建节点属性),以确保颜色以与G.nodes() 中相同的顺序出现,这样可以确保正确的颜色与正确的颜色对齐节点:
G = nx.from_pandas_edgelist(edges_df, source='Node', target='Edge')
# Then draw with colours based on the Series:
nx.draw(G,
node_color=colour_map.reindex(G.nodes()),
with_labels=True)
无论哪种方法,我们都会得到如下图: