带有颜色标签和c选项指定的图例的matplotlib散点图

时间:2017-10-29 23:19:30

标签: python matplotlib plot legend

我想制作this kind of scatter plot,其中的点具有由" c"指定的颜色。选项和图例显示颜色的含义。

我的数据来源如下:

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()

不幸的是,我没有像预期的那样得到传奇。如何正确显示图例?我预计有五行,每行显示颜色和组对应。

enter image description here

2 个答案:

答案 0 :(得分:5)

如您所提及的示例所示,请为每个组致电plt.scatter

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()

enter image description here

答案 1 :(得分:1)

检查一下:

import matplotlib.pyplot as plt
import numpy as  np

fig, ax = plt.subplots()
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])
for g in np.unique(group):
    i = np.where(group == g)
    ax.scatter(scatter_x[i], scatter_y[i], label=g)
ax.legend()
plt.show()