基于networkx中边缘颜色的图例

时间:2018-01-02 17:51:37

标签: python matplotlib legend networkx

有没有办法根据边缘颜色(而不是节点颜色)在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, 'Order') 但是我如何把它变成一个传奇?

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

1 个答案:

答案 0 :(得分:0)

您可以采用的一种方式是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

的内容
相关问题