Matplotlib:仅显示图例的唯一标签

时间:2015-06-23 01:12:41

标签: python matplotlib

假设我有一个X(X.shape = [N,2])和标签(labels.shape = N)的数组。 我想生成X [:,0],X [:,1]的散布,与标签对应的颜色,只显示唯一标签。

代码:

import numpy as np
from numpy.random import rand

import matplotlib
from matplotlib import pyplot as plt
%matplotlib inline

import seaborn as sns
sns.set(context='poster', style='dark')

X = rand(500)
Y = rand(500)
labels = np.round(rand(500)*4).astype(int)
print(np.unique(labels)) # array([0, 1, 2, 3, 4])

plt.scatter(X, Y, c=labels, cmap='rainbow') # this does what I want minus the labels

plt.scatter(X, Y, c=labels, cmap='rainbow', label=labels)
plt.legend(loc='best') # this produces 500 labels instead of 5

1 个答案:

答案 0 :(得分:0)

您可以单独绘制每个标签。您需要从cmap中选择颜色,您需要先将其标准化为标签。

import numpy as np
from numpy.random import rand

import matplotlib.pyplot as plt
from matplotlib import cm, colors
%matplotlib inline

import seaborn as sns
sns.set(context='poster', style='dark')

X = rand(500)
Y = rand(500)
labels = np.round(rand(500)*4).astype(int)
unique_labels=np.unique(labels) # array([0, 1, 2, 3, 4])

norm = colors.Normalize(vmin=unique_labels[0], vmax=unique_labels[-1])
m = cm.ScalarMappable(norm=norm, cmap=cm.rainbow)

for label in np.unique(labels):
    color = m.to_rgba(label)
    plt.scatter(X[labels==label], Y[labels==label], c=color, label=label)

plt.legend(loc='best')

产生这个(没有seaborn,因为我没有安装,但你明白了): enter image description here