以下是基于空手道俱乐部图表的演示:
import pandas as pd
import networkx as nx
import matplotlib.pyplot as plt
G = nx.karate_club_graph()
df = (pd.DataFrame(list(G.degree), columns=['node','degree'])
.set_index('node'))
df['club'] = pd.Series({node:data['club']
for node,data in G.nodes(data=True)})
df['color'] = df.groupby('club')['degree'].transform(lambda c: c/c.max())
df.loc[df['club']=='Officer', 'color'] *= -1
layout = nx.fruchterman_reingold_layout(G)
vmin = df['color'].min()
vmax = df['color'].max()
cmap = plt.cm.coolwarm
nx.draw_networkx(G, pos=layout, with_labels=True, node_color=df['color'],
cmap=cmap, vmin=vmin, vmax=vmax)
sm = plt.cm.ScalarMappable(cmap=cmap, norm=plt.Normalize(vmin=vmin, vmax=vmax))
sm.set_array([])
cbar = plt.colorbar(sm)
结果: