【问题标题】:NetworkX python中基于边缘颜色的图例
【发布时间】:2021-12-29 17:57:55
【问题描述】:

我在添加基于边缘颜色的图例时遇到了麻烦,因为我是 python 和 networkX 的新手。 我有一个 excel 表,其中一个边缘属性是颜色的模型,指示边缘的颜色(如果是卡车,则为黄色,船舶为蓝色等)。但是,我的代码没有正确执行图例逻辑。图例显示为另一个图。

我尝试使用 nx.draw_networkx_edges 但我无法弄清楚。

这是代码:

fig, ax = plt.subplots(figsize=(10, 5))
plt.title('Transportation Network', size=15)
#nx.draw_networkx_labels(GR, pos_dict)
nx.draw(g, pos=node_positions, edge_color=edge_colors, node_size=40, node_color='black', ax=ax)

plt.xlabel('Time ( 1 epoch= 15 mins)')
plt.ylabel("Cities")
ax.set_axis_on()
ax.tick_params(left=True, bottom=True, labelleft=True, labelbottom=True )
plt.locator_params(axis="y", nbins=3)
plt.locator_params(axis="x", nbins=30)
ax.set_yticks([10,20,30])
ax.set_yticklabels(['DB','AD','AA'])
plt.show()

plt.plot(edgelist["Color"], "Yellow", label="Truck")
plt.plot(edgelist["Color"], "Green", label="Train")
plt.plot(edgelist["Color"], "Blue", label="Ship")
plt.legend()

【问题讨论】:

    标签: python matplotlib networkx legend


    【解决方案1】:

    您可以通过虚拟Line2D 对象创建custom legend

    要使黄色更明显,您可以将其替换为'Gold'

    edge_colors = ['Gold' if c == 'Yellow' else c for c in edge_colors]
    

    要添加自定义图例,在 ax.set_yticklabels(['DB','AD','AA']) 之后的代码中,您可以将剩余代码替换为:

    from matplotlib.lines import Line2D
    
    handles = [Line2D([], [], color=color, label=label)
               for color, label in zip(["Gold", "Green", "Blue"], ["Truck", "Train", "Ship"])]
    ax.legend(handles=handles)
    plt.show()
    

    【讨论】:

    • 约翰,你是个救星!!
    • 我不知道!谢谢你通知我。然后我会为第二个问题这样做:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2013-07-12
    • 2018-04-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多