简体   繁体   English

将图例添加到散点图中

[英]Add legend to scatter plot

This question has been asked on SO, but I want to find a clearer solution. 这个问题已在SO上提出,但我想找到一个更清晰的解决方案。

Given X is 100x2 data, and labels is the label vector ( from 1 to 9) I plot the scatter plot as following: 给定X是100x2数据,标签是标签向量(从1到9)我绘制散点图如下:

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

在此输入图像描述

How to add legend to explain the colors in just one line of code? 如何在一行代码中添加图例来解释颜色? Other solutions plot each label separately: 其他解决方案分别绘制每个标签

a = pl.scatter(X1[:,0], X1[:,1], color = "red")
b = pl.scatter(X2[:,0], X2[:,1], color = "green")
c = pl.scatter(X3[:,0], X3[:,1], color = "blue")
pl.legend((a,b,c), ("line 1", "line 2", "line 3")
pl.show()

You could create a dummy scatter plot with the desired legend as follows: 您可以使用所需的图例创建虚拟散点图,如下所示:

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()

Just label each plot and invoke legend() as you do :) 只需标记每个绘图并像你一样调用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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM