设置与pyplot.scatter中的颜色匹配的图例 [英] setting a legend matching the colours in pyplot.scatter
问题描述
假设我的数据按以下方式组织:
Suppose my data is organized in the following way:
x_values = [6.2, 3.6, 7.3, 3.2, 2.7]
y_values = [1.5, 3.2, 5.4, 3.1, 2.8]
colours = [1, 1, 0, 1, -1]
labels = ["a", "a", "b", "a", "c"]
我想用这个做一个散点图:
I want to make a scatterplot with this:
axis = plt.gca()
axis.scatter(x_values, y_values, c=colours)
我想要一个具有3个类别的图例:"a","b"和"c".
I want a legend with 3 categories: "a", "b" and "c".
鉴于此列表中的类别与 colours
列表中的点的顺序相匹配,我可以使用 labels
列表来制作此图例吗?
Can I use the labels
list to make this legend, given that the categories in this list match the order of the points in the colours
list?
我是否需要为每个类别分别运行 scatter
命令?
Do I need to run the scatter
command separately for each category?
推荐答案
如果要使用色图,则可以为 colors
列表中的每个唯一条目创建一个图例条目,如下所示.这种方法适用于任何数量的值.图例句柄是 plot
的标记,以便它们与散点匹配.
If you want to use a colormap you can create a legend entry for each unique entry in the colors
list as shown below. This approach works well for any number of values. The legend handles are the markers of a plot
, such that they match with the scatter points.
import matplotlib.pyplot as plt
x_values = [6.2, 3.6, 7.3, 3.2, 2.7]
y_values = [1.5, 3.2, 5.4, 3.1, 2.8]
colors = [1, 1, 0, 1, -1]
labels = ["a", "a", "b", "a", "c"]
clset = set(zip(colors, labels))
ax = plt.gca()
sc = ax.scatter(x_values, y_values, c=colors, cmap="brg")
handles = [plt.plot([],color=sc.get_cmap()(sc.norm(c)),ls="", marker="o")[0] for c,l in clset ]
labels = [l for c,l in clset]
ax.legend(handles, labels)
plt.show()
这篇关于设置与pyplot.scatter中的颜色匹配的图例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!