[英]matplotlib add legend with multiple entries for a single scatter plot
我正在为如下所示的数据集制作散点图 plot:
x = [1, 1, 2, 2, 3, 3, 4, 4]
y = [1, 2, 3, 4, 1, 2, 3, 4]
labels = [1, 3, 0, 2, 2, 1, 0, 3]
colors = np.array(plt.rcParams['axes.prop_cycle'].by_key()['color'])
plt.scatter(x, y, color=colors[labels])
如果我调用plt.legend
,对于整个数据集,将只显示一个条目,并带有第一个符号。 如何创建一个包含所有四个元素的图例,就像我绘制了四个单独的数据集一样显示?
您可以为标签集提供 plot 空列表:
for l in set(labels):
plt.scatter([],[], color=colors[l], label=l)
plt.legend()
我认为整体最简单的解决方案是将所有工作委托给 matplotlib。 该方法在此处描述: https://matplotlib.org/gallery/lines_bars_and_markers/scatter_with_legend.html#automated-legend-creation 。 对于这种简化的方法,您只需要使用PathCollection
的legend_elements
方法:
s = plt.scatter(x, y, c=labels)
plt.legend(*s.legend_elements())
更改颜色图或将标签替换为其他内容(例如文本)很简单:
text_labels = ['one', 'two', 'three', 'four']
s = plt.scatter(x, y, c=labels, cmap='jet', vmin=0, vmax=4)
plt.legend(s.legend_elements()[0], text_labels)
如果labels
还不是[0-n)
范围内的元素的排序数组,则可以使用np.unique
轻松获得:
labels = ['b', 'd', 'a', 'c', 'c', 'b', 'a', 'd']
text_labels, labels = np.unique(labels, return_inverse=True)
只是实现预期结果的另一种方式。 我使用此解决方案摆脱了重复项
for i, j, l in zip(x, y, labels):
plt.scatter(i, j, c=colors[l], label=l)
handles, labels = plt.gca().get_legend_handles_labels()
by_label = dict(zip(labels, handles))
plt.legend(by_label.values(), by_label.keys())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.