添加散点图例

2024-04-16 19:44:07 发布

您现在位置:Python中文网/ 问答频道 /正文

有人问过这个问题,但我想找到一个更清楚的解决办法。在

给定X是100x2的数据,labels是标签向量(从1到9),我绘制散点图如下:

pl.scatter(X[:,0], X[:,1], c = labels)
pl.show()

enter image description here

如何在一行代码中添加图例来解释颜色?其他解决方案分别绘制每个标签:

^{pr2}$

Tags: 数据代码labels颜色show绘制标签解决方案
2条回答

只需标记每个绘图并像您所做的那样调用legend()。)

plt.scatter(x1,y1,label=str(pointset1))
plt.scatter(x2,y2,label=str(pointset2))
plt.scatter(x3,y3,label=str(pointset3))

plt.legend(loc='upper right', numpoints=1, ncol=3, fontsize=8, bbox_to_anchor=(1,1))
plt.show()

可以使用所需图例创建虚拟散点图,如下所示:

pl.scatter(X[:,0], X[:,1], c = labels)

for item in labels:
    #dummy plot just to create the legend
    pl.scatter([], [], c = item, label = item)
#loc = 0 is for the best position of the legend
#scatterpoints = 1 will only show one point in the legend instead of multiple points
plt.legend(loc = 0, scatterpoints = 1)
pl.show()

相关问题 更多 >