matplotlib c选项指定的颜色标签和图例的散点图[重复]

5lwkijsr  于 2023-05-18  发布在  其他
关注(0)|答案(2)|浏览(248)

此问题已在此处有答案

Scatter plot with legend for each color in c(5个答案)
5年前关闭。
我想使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()

不幸的是,我没有像预期的那样得到传说。如何正确地展示传奇?我希望有五行,每一行显示颜色和组对应关系。

ybzsozfc

ybzsozfc1#

正如你提到的例子,为每个组调用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()

bcs8qyzn

bcs8qyzn2#

看看这个

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

相关问题