我在对关系图进行聚类分析,并使用networkx
来可视化结果:
G = nx.from_numpy_matrix(X)layout = nx.fruchterman_reingold_layout(G)nx.draw_networkx(G, pos=layout, with_labels=True, node_color=predict, cmap=plt.cm.coolwarm, vmin=0, vmax=1)
是否可以添加颜色条?直接使用plt.colorbar()
会引发错误:
RuntimeError: No mappable was found to use for colorbar creation. First define a mappable such as an image (with imshow) or a contour set (with contourf).
在文档中没有找到相关的选项。我也愿意考虑使用其他兼容Python 3的包来进行可视化。
回答:
以下是一个基于空手道俱乐部图的演示:
import pandas as pdimport networkx as nx import matplotlib.pyplot as pltG = 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'] *= -1layout = nx.fruchterman_reingold_layout(G)vmin = df['color'].min()vmax = df['color'].max()cmap = plt.cm.coolwarmnx.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)
结果: