具有由c选项指定的颜色标签和图例的matplotlib散点图 [英] matplotlib scatter plot with color label and legend specified by c option

查看:101
本文介绍了具有由c选项指定的颜色标签和图例的matplotlib散点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想制作这种散点图具有通过"c"选项指定的颜色,图例显示了颜色的含义.

I'd like to make this kind of scatter plot where the points have colors specified by the "c" option and the legend shows the color's meanings.

我的数据源如下:

scatter_x = [1,2,3,4,5]
scatter_y = [5,4,3,2,1]
group = [1,3,2,1,3] # each (x,y) belongs to the group 1, 2, or 3.

我尝试过:

plt.scatter(scatter_x, scatter_y, c=group, label=group)
plt.legend()

不幸的是,我没有得到预期的图例.如何正确显示图例?我希望有五行,每行显示颜色和组对应关系.

Unfortunately, I did not get the legend as expected. How to show the legend properly? I expected there are five rows and each row shows the color and group correspondences.

推荐答案

如您在示例中所述,为每个组调用plt.scatter:

As in the example you mentioned, call plt.scatter for each group:

import numpy as np
from matplotlib import pyplot as plt

scatter_x = np.array([1,2,3,4,5])
scatter_y = np.array([5,4,3,2,1])
group = np.array([1,3,2,1,3])
cdict = {1: 'red', 2: 'blue', 3: 'green'}

fig, ax = plt.subplots()
for g in np.unique(group):
    ix = np.where(group == g)
    ax.scatter(scatter_x[ix], scatter_y[ix], c = cdict[g], label = g, s = 100)
ax.legend()
plt.show()

这篇关于具有由c选项指定的颜色标签和图例的matplotlib散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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