Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/280.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 向散点图添加图例_Python_Matplotlib_Legend_Scatter Plot - Fatal编程技术网

Python 向散点图添加图例

Python 向散点图添加图例,python,matplotlib,legend,scatter-plot,Python,Matplotlib,Legend,Scatter Plot,这个问题已经被问到了,但我想找到一个更清楚的解决办法 给定X是100x2数据,标签是标签向量(从1到9),我绘制散点图如下: pl.scatter(X[:,0], X[:,1], c = labels) pl.show() 如何添加图例来解释一行代码中的颜色?其他解决方案分别绘制每个标签: a = pl.scatter(X1[:,0], X1[:,1], color = "red") b = pl.scatter(X2[:,0], X2[:,1], color = "green") c =

这个问题已经被问到了,但我想找到一个更清楚的解决办法

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

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

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

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

只需标记每个绘图并调用图例(),就像您所做的那样:)


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

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

我知道您可能已经看到了这一点,但如果您没有看到:只需标记每个绘图并调用图例():plt.scatter(x1,y1,label=str(pointset1))。。。;plt.图例(loc='右上角',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()