gpt4 book ai didi

python - networkx 中基于边缘颜色的图例

转载 作者:行者123 更新时间:2023-12-05 09:17:24 25 4
gpt4 key购买 nike

有没有办法根据边颜色(而不是节点颜色)在 networkx 中创建图例?

这是我的图表:

plt.figure(figsize = (15, 10))
G = nx.from_pandas_dataframe(df, 'From', 'To', ['Order', 'Colors'])
edge_labels = nx.get_edge_attributes(G, 'Order')
nx.draw_networkx(G, with_labels = False, node_color = 'black', alpha = 0.5, node_size = 3, linewidths = 1, edge_color = df['Colors'], edge_cmap =
plt.cm.Set2)
plt.show()

其中,['Order'] 是边的描述符,['Color'] 是映射到 [ 中每个值的唯一整数'Order'],它正在根据 Set2 颜色图创建边缘颜色。

我可以通过以下方式获得边缘标签: edge_labels = nx.get_edge_attributes(G, '订单')但如何将其放入图例中?

如果有帮助,我很乐意分享数据和完整代码!

最佳答案

一种方法是本着 this SO answer 的精神它为图例中的 LineCollection 的每个成员使用代理。

您可以使用分步绘图函数获取LineCollection,分别绘制节点和边(例如draw_networkx_nodes doc。)

import matplotlib.pyplot as plt
import networkx as nx
from matplotlib.lines import Line2D

# make a test graph
n = 7 # nodes
m = 5 # edges
G = nx.gnm_random_graph(n, m)
# and define some color strings (you'll get this array from the dataframe)
_c = 'rgbcmky' * m # way too many colors, trim after
clrs = [c for c in _c[:m]]

plt.ion()

plt.figure(figsize = (9, 7), num=1); plt.clf()
# draw the graph in several steps
pos = nx.spring_layout(G)
h1 = nx.draw_networkx_nodes(G, pos=pos, node_color = 'black',
alpha = 0.9, node_size = 300, linewidths=6)
# we need the LineCollection of the edges to produce the legend (h2)
h2 = nx.draw_networkx_edges(G, pos=pos, width=6, edge_color=clrs)

# and just show the node labels to check the labels are right!
h3 = nx.draw_networkx_labels(G, pos=pos, font_size=20, font_color='c')


#https://stackoverflow.com/questions/19877666/add-legends-to-linecollection-plot - uses plotted data to define the color but here we already have colors defined, so just need a Line2D object.
def make_proxy(clr, mappable, **kwargs):
return Line2D([0, 1], [0, 1], color=clr, **kwargs)

# generate proxies with the above function
proxies = [make_proxy(clr, h2, lw=5) for clr in clrs]
# and some text for the legend -- you should use something from df.
labels = ["{}->{}".format(fr, to) for (fr, to) in G.edges()]
plt.legend(proxies, labels)

plt.show()

这会产生如下内容:example use of proxies in legend for networkx

关于python - networkx 中基于边缘颜色的图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48065567/

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