Python matplotlib为单个散点图添加具有多个条目的图例

Python matplotlib为单个散点图添加具有多个条目的图例,python,matplotlib,legend,Python,Matplotlib,Legend,我正在为数据集绘制散点图,如下所示: 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,对于整个数据集,只有一个

我正在为数据集绘制散点图,如下所示:

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
,对于整个数据集,只有一个条目显示第一个符号。如何创建包含所有四个元素的图例,并将其显示为绘制了四个单独的数据集

可能相关:

基于:

您可以为标签集绘制空列表:

for l in set(labels):
    plt.scatter([],[], color=colors[l], label=l)
plt.legend()

这只是实现预期结果的另一种方式。我使用解决方案消除了重复项


我认为最简单的解决方案是将所有工作委托给matplotlib。此处描述了该方法:。对于这种简化方法,只需使用方法即可:

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)

如果
标签
还不是范围
[0-n)
中的元素排序数组,则可以使用以下方法轻松获得:


这绝对是个好主意。如果我不标记原始数据集,它就不会出现在图例中。我想我找到了一种可以说比这更有效的内置方法。从技术上说,是的,但我确实在努力避免将每个点都放在一个单独的对象中。我觉得这不会很好地扩展。我想我找到了一种内置方法。我从来没有这样做过我知道matplotlib是为你做的。
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 = ['b', 'd', 'a', 'c', 'c', 'b', 'a', 'd']
text_labels, labels = np.unique(labels, return_inverse=True)