gpt4 book ai didi

python - 如何在networkx.draw_networkx中获取颜色条?

转载 作者:行者123 更新时间:2023-11-30 08:39:40 24 4
gpt4 key购买 nike

我正在关系图上执行聚类,目前正在使用 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)

enter image description here

是否可以获得颜色条?只需使用 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).

documentation 中没有任何选项。我也愿意使用另一个包进行可视化,只要它与 Python 3 兼容。

最佳答案

这是一个基于空手道俱乐部图的演示:

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)

结果:

enter image description here

关于python - 如何在networkx.draw_networkx中获取颜色条?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49572089/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com