我无法在图集中添加图例。 颜色由采用两个值0或1的变量y编码的问题。 X来自PCA方法,我尝试绘制2个主成分,它们具有对应于不同y的不同颜色。 我收到错误消息“没有找到带有放置在图例中的标签的句柄。”
尝试了不同的教程,但仍然很困惑。
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()
答案 0 :(得分:1)
如果您使用的是Matplotlib的较新版本(> = 3.1),则可以按照以下答案将图例添加到散点图:Scatterplot legends
否则,一种解决方法是分别对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()