Python matplotlib散点图,带颜色标签和图例,由c选项指定
我想指出点的颜色由“c”选项指定,图例显示了颜色的含义 我的数据来源如下:Python matplotlib散点图,带颜色标签和图例,由c选项指定,python,matplotlib,plot,legend,Python,Matplotlib,Plot,Legend,我想指出点的颜色由“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() 不幸的是,我没有得到传说中的预期。如何正
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()
不幸的是,我没有得到传说中的预期。如何正确显示图例?我希望有五行,每行显示颜色和组对应
如您提到的示例所示,为每组调用
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()
查看以下内容:
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()
您可以使用
ax.legend()
来保持一致:)编辑-谢谢。还更新了Python3.6.1的图。np.unique()/np.where(group==g)
有效,并且是在本机numpy
中不使用helper libs的唯一方法。这是一种非常复杂的方法,可以不使用循环就完成group\u by()
吗?类似于ax.scatter(…,label=list\u of\u group\u labels)
?@Sos我认为这是一个单独的问题,但答案是seaborn.scatterplot