天天看点

python加颜色_python – 向网络图添加图例以解释节点的颜色

我有一个networkx图的图,其中边缘颜色取决于使用以下代码分配给相应边的权重(使用a_netw nx.Graph):

a_netw_edges = a_netw.edges()

a_netw_weights = [a_netw[source][dest]['weight'] for source, dest in a_netw_edges]

a_netw_colors = [plt.cm.Blues(weight*15) for weight in a_netw_weights]

nx.draw_networkx(a_netw, edges=a_netw_edges, width=1, edge_color=a_netw_colors)

在这张图中,我想添加一个图例,使权重和颜色之间的连接显式;就像在使用pcolor的热图中一样.

虽然我对如何开始有一个粗略的想法:

fig, axes = plt.subplots(nrows=2)

nx.draw_networkx(a_netw, edges=a_netw_edges, width=1, edge_color=a_netw_colors, ax=axes[0])

axes[0].get_xaxis().set_visible(False)

axes[0].get_yaxis().set_visible(False)

gradient = np.linspace(0, 1, 256)

gradient = np.vstack((gradient, gradient))

axes[1].imshow(gradient, aspect=3, cmap=plt.cm.Blues)

axes[1].get_yaxis().set_visible(False)

plt.tight_layout()

我不知道如何执行以下步骤:

>在相关轴上添加正确的刻度以获得与权重的连接.

>垂直绘制而不是水平绘制.

解决方法:

我建议你使用colorbar()命令,如下所示.我提供了一个示例Graph,看看它是否有意义?

python加颜色_python – 向网络图添加图例以解释节点的颜色

import networkx as nx

import matplotlib.pyplot as plt

#generate a graph with weights

a_netw=nx.Graph()

a_netw.add_edge('a','b',weight=6)

a_netw.add_edge('a','c',weight=2)

a_netw.add_edge('c','d',weight=1)

a_netw.add_edge('c','e',weight=7)

a_netw.add_edge('c','f',weight=9)

a_netw.add_edge('a','d',weight=3)

#creating a color list for each edge based on weight

a_netw_edges = a_netw.edges()

a_netw_weights = [a_netw[source][dest]['weight'] for source, dest in a_netw_edges]

#scale weights in range 0-1 before assigning color

maxWeight=float(max(a_netw_weights))

a_netw_colors = [plt.cm.Blues(weight/maxWeight) for weight in a_netw_weights]

#suppress plotting for the following dummy heatmap

plt.ioff()

#multiply all tuples in color list by scale factor

colors_unscaled=[tuple(map(lambda x: maxWeight*x, y)) for y in a_netw_colors]

#generate a 'dummy' heatmap using the edgeColors as substrate for colormap

heatmap = plt.pcolor(colors_unscaled,cmap=plt.cm.Blues)

#re-enable plotting

plt.ion()

fig,axes = plt.subplots()

nx.draw_networkx(a_netw, edges=a_netw_edges, width=10, edge_color=a_netw_colors, ax=axes)

axes.get_xaxis().set_visible(False)

axes.get_yaxis().set_visible(False)

#add colorbar

cbar = plt.colorbar(heatmap)

cbar.ax.set_ylabel('edge weight',labelpad=15,rotation=270)

标签:python,matplotlib,networkx

来源: https://codeday.me/bug/20190628/1310605.html