带图例的t-sne散点图

时间:2018-09-12 14:41:46

标签: matplotlib plot legend scatter

我的代码

X:无答案的数据集

y:答案(0、1、2或3)

%matplotlib inline
import matplotlib.pyplot as plt
from sklearn.manifold import TSNE
X_reduced = TSNE(n_components=2, perplexity=113.0,random_state=0).fit_transform(X)
plt.scatter(X_reduced[:, 0], X_reduced[:, 1], c=y, cmap='Greens')
plt.legend(["A","B","C","D"], loc='best')

然后我得到了 this

但是我希望带有A,B,C,D的“传奇”对应每种颜色(浅绿色到深绿色)

如果您能回答这个问题,我将不胜感激。

2 个答案:

答案 0 :(得分:1)

这是我发现的最简单的方法。

给出类标签列表labels = ['A', 'B', 'C']和类似y的数组类索引:

transformed = tsne_model.fit_transform(X)

scatter = plt.scatter(transformed[:,0], transformed[:,1], c=y)
handles, _ = scatter.legend_elements(prop='colors')
plt.legend(handles, labels)

答案 1 :(得分:0)

如果y表示类别。那么最简单的方法是遍历y的不同值,并在传递标签时用标准plt.plot绘制点:

# make a mapping from category to your favourite colors and labels
category_to_color = {0: 'lightgreen', 1: 'lawngreen', 2:'limegreen', 3: 'darkgreen'}
category_to_label = {0: 'A', 1:'B', 2:'C', 3:'D'}

# plot each category with a distinct label
fig, ax = plt.subplots(1,1)
for category, color in category_to_color.items():
    mask = y == category
    ax.plot(X_reduced[mask, 0], X_reduced[mask, 1], 'o', 
            color=color, label=category_to_label[category])

ax.legend(loc='best')