编码颜色时将图例添加到散点图

Adding legend to scatterplot when color is encoded

我无法在我的散点图中添加图例。 颜色由变量 y 编码的问题,它有两个值 0 或 1。 X来自PCA方法,我尝试绘制2个不同颜色对应不同y的主成分。 我收到错误消息 "No handles with labels found to put in legend."

尝试了不同的教程,但还是一头雾水。

fig = plt.figure(figsize=(10,5))
ax = fig.add_subplot(111)

plt.scatter(x_reduced[:,0], x_reduced[:,1],c=y, alpha=0.5)

plt.legend()
plt.show()

如果您使用的是较新版本的 Matplotlib (>=3.1),则可以按照以下答案将图例添加到散点图中:

否则,解决方法是对 plt.scatter

进行两次单独调用
# one scatter for y == 0
plt.scatter(x_reduced[y==0,0], x_reduced[y==0,1], alpha=0.5, label = "group1")
# another scatter for y == 1
plt.scatter(x_reduced[y==1,0], x_reduced[y==1,1], alpha=0.5, label = "group2")

# create legend for both
plt.legend()