Tok*_*rby 1 python machine-learning matplotlib networkx python-3.x
我正在对关系图执行聚类,目前正在使用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)
Run Code Online (Sandbox Code Playgroud)
是否有可能获得颜色条?简单地使用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 兼容。
Here is a demo based on Karate Club graph:
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)
Run Code Online (Sandbox Code Playgroud)
Result:
| 归档时间: |
|
| 查看次数: |
2306 次 |
| 最近记录: |