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?
这是我目前的代码:
import matplotlib.pyplot as plt
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)
plt.show()
推荐答案
首先,我有一种感觉,您打算在声明颜色时使用撇号,而不是反引号.
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)
还有第二种创建图例的方法,您可以在其中指定标签".对于一组点,对每组使用单独的分散命令.下面给出了一个例子.
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 文档时发现的.由于图例覆盖了数据点,我移动了它们,图例的位置可以在 here.如果有另一种制作图例的方法,我在文档中快速搜索了几次后找不到它.
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屋!