且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Matplotlib 散点图与图例

更新时间:2022-05-25 23:00:02

首先,我有一种感觉,您打算在声明颜色时使用撇号,而不是反引号.

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.