matplotlib为单个散点图添加带有多个条目的图例 [英] matplotlib add legend with multiple entries for a single scatter plot

查看:90
本文介绍了matplotlib为单个散点图添加带有多个条目的图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am making a scatter plot for a dataset that looks like this:

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 ,则对于整个数据集,只会显示一个条目,并带有第一个符号.如何创建包含所有四个元素的图例,就像我绘制了四个单独的数据集一样显示?

If I call plt.legend, only one entry will be shown, for the entire dataset, with the first symbol. How do I create a legend with all four elements in it, displayed as if I had plotted four separate datasets?

可能相关:具有多个图例条目的Matplotlib直方图
基于: Matplotlib,如何循环?

推荐答案

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

You can plot empty lists for the set of labels:

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

这篇关于matplotlib为单个散点图添加带有多个条目的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆