基于节点属性向 NetworkX 图添加图例(使用 matplotlib)

Add legend to NetworkX graph (using matplotlib) based on node attribute

我在向 NetworkX 图添加图例时遇到问题(已经检查了之前的问题,但到目前为止,问题和答案仅针对半相关问题)。

我希望能够根据节点属性映射我的网络并为节点着色(在我在这里使用的示例中,属性是 'sex' (m/f) 但我也有具有更多类别或数字的属性)。我还想要一个图例来显示哪种颜色代表哪个类别(在分类属性的情况下)。

到目前为止,我已经能够根据属性为节点着色,但无法为图表添加图例。我尝试了很多东西,但似乎没有任何效果!有人对我如何添加图例有任何建议吗?

到目前为止,这是我的代码:

nodes_colors = []
for node in property_crime.nodes:
   if property_crime.nodes[node]["sex"] == "f":
       nodes_colors.append('blue')
   else:
       nodes_colors.append('orange')

nx.draw(property_crime, node_color=nodes_colors, node_size=15)
plt.show()

这是返回的图像:enter image description here

请注意,'property_crime' 是一个图形对象。该图是无向的,没有加权。

感谢您的帮助!

尝试在 plt.show() 之前添加这些行:

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

legend_elements = [Line2D([0], [0], marker='o', color='blue', label='Female', lw=0,
                          markerfacecolor='blue', markersize=10),
                   Line2D([0], [0], marker='o', color='orange', label='Male', lw=0,
                          markerfacecolor='orange', markersize=10)]
ax = plt.gca()
ax.legend(handles=legend_elements, loc='upper right')