将图例添加到散点图 [英] Add legend to scatter plot

查看:353
本文介绍了将图例添加到散点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人问过这个问题,但是我想找到一个更清晰的解决方案.

This question has been asked on SO, but I want to find a clearer solution.

鉴于X是100x2数据,而labels是标签向量(从1到9),我将散点图绘制如下:

Given X is 100x2 data, and labels is the label vector ( from 1 to 9) I plot the scatter plot as following:

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

这篇关于将图例添加到散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆