使用matplotlib中样本的标签为散点图创建图例 [英] Create legend for scatter plot using the label of the samples in matplotlib

查看:180
本文介绍了使用matplotlib中样本的标签为散点图创建图例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用matplotlib中的散点图来绘制一些点.我有两个一维数组,每个数组存储样本的x和y坐标.另外还有一个一维数组,用于存储标签(以决定应以哪种颜色绘制点).到目前为止,我编程了:

I am using scatter plot in matplotlib to plot some points. I have two 1D arrays each storing the x and y coordinate of the samples. Also there is another 1D array that stores the label(to decide in which colour the point should be plotted). I programmed thus far:

import matplotlib.pyplot as plt
X = [1,2,3,4,5,6,7]
Y = [1,2,3,4,5,6,7]
label = [0,1,4,2,3,1,1]
plt.scatter(X, Y, c= label, s=50)
plt.show()

现在我希望能够看到哪种颜色对应于哪个标签? 我在matplotlib中查找了图例的实现,如下所示: 如何为scatter()添加图例? 但是,他们建议为每个样本标签创建一个图.但是我所有的标签都在同一个一维数组(标签)中.我怎样才能做到这一点?

Now I want to be able to see which color corresponds to which label? I looked up the implementation of legends in matplotlib like the one here: how to add legend for scatter()? However they are suggesting to create a plot for each label of sample. However all my labels are in the same 1D array(label). How can I achieve this?

推荐答案

您可以使用色图来实现. 此处.

You could do it with a colormap. Some examples of how to do it are here.

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.colors as colors
X = [1,2,3,4,5,6,7]
Y = [1,2,3,4,5,6,7]
label = [0,1,4,2,3,1,1]

# Define a colormap with the right number of colors
cmap = plt.cm.get_cmap('jet',max(label)-min(label)+1)

bounds = range(min(label),max(label)+2)
norm = colors.BoundaryNorm(bounds, cmap.N)

plt.scatter(X, Y, c= label, s=50, cmap=cmap, norm=norm)

# Add a colorbar. Move the ticks up by 0.5, so they are centred on the colour.
cb=plt.colorbar(ticks=np.array(label)+0.5)
cb.set_ticklabels(label)

plt.show()

您可能需要四处游动,以使刻度线标签的颜色居中,但您明白了.

You might need to play around to get the tick labels centred on their colours, but you get the idea.

这篇关于使用matplotlib中样本的标签为散点图创建图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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