Matplotlib散点图与图例 [英] Matplotlib scatter plot with legend
问题描述
我想创建一个Matplotlib散点图,并用图例显示每个类的颜色.例如,我有一个x
和y
值的列表,以及一个classes
值的列表. x
,y
和classes
列表中的每个元素对应于图中的一个点.我希望每个类都具有自己的颜色(已经进行了编码),但是然后我希望这些类在图例中显示.我应将什么参数传递给legend()
函数以实现此目的?
I want to create a Matplotlib scatter plot, with a legend showing the colour for each class. For example, I have a list of x
and y
values, and a list of classes
values. Each element in the x
, y
and classes
lists corresponds to one point in the plot. I want each class to have its own colour, which I have already coded, but then I want the classes to be displayed in a legend. What paramaters do I pass to the legend()
function to achieve this?
到目前为止,这是我的代码:
Here is my code so far:
x = [1, 3, 4, 6, 7, 9]
y = [0, 0, 5, 8, 8, 8]
classes = ['A', 'A', 'B', 'C', 'C', 'C']
colours = ['r', 'r', 'b', 'g', 'g', 'g']
plt.scatter(x, y, c=colours)
推荐答案
首先,我觉得您在声明颜色时应该使用撇号,而不是反引号.
First, I have a feeling you meant to use apostrophes, not backticks when declaring colours.
对于图例,您需要一些形状以及类.例如,下面为class_colours
中的每种颜色创建一个称为recs
的矩形的列表.
For a legend you need some shapes as well as the classes. For example, the following creates a list of rectangles called recs
for each colour in class_colours
.
import matplotlib.patches as mpatches
classes = ['A','B','C']
class_colours = ['r','b','g']
recs = []
for i in range(0,len(class_colours)):
recs.append(mpatches.Rectangle((0,0),1,1,fc=class_colours[i]))
plt.legend(recs,classes,loc=4)
如果需要,您也可以使用圆圈,只需查看matplotlib.patches
文档即可.还有第二种创建图例的方法,其中,您可以为每个点使用单独的散点命令为一组点指定标签".下面是一个示例.
You could use circles too if you wanted, just check out the matplotlib.patches
documentation. There is a second way of creating a legend, in which you specify the "Label" for a set of points using a separate scatter command for each set. An example of this is given below.
classes = ['A','A','B','C','C','C']
colours = ['r','r','b','g','g','g']
for (i,cla) in enumerate(set(classes)):
xc = [p for (j,p) in enumerate(x) if classes[j]==cla]
yc = [p for (j,p) in enumerate(y) if classes[j]==cla]
cols = [c for (j,c) in enumerate(colours) if classes[j]==cla]
plt.scatter(xc,yc,c=cols,label=cla)
plt.legend(loc=4)
第一种方法是我个人使用的方法,第二种方法是我在查看matplotlib文档时才发现的.由于图例覆盖了数据点,因此我将它们移动了,并且可以在此处找到图例的位置.如果还有另一种制作图例的方法,则在文档中进行了几次快速搜索后,我无法找到它.
The first method is the one I've personally used, the second I just found looking at the matplotlib documentation. Since the legends were covering datapoints I moved them, and the locations for legends can be found here. If there's another way to make a legend, I wasn't able to find it after a few quick searches in the docs.
这篇关于Matplotlib散点图与图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!