设置与pyplot.scatter中的颜色匹配的图例

时间:2017-05-24 16:38:03

标签: python matplotlib

假设我的数据按以下方式组织:

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"]

我想用这个制作一个散点图:

axis = plt.gca()
axis.scatter(x_values, y_values, c=colours)

我想要一个包含3个类别的传奇:" a"," b"和" c"。

我是否可以使用labels列表制作此图例,因为此列表中的类别与colours列表中的点的顺序相匹配?

我是否需要为每个类别单独运行scatter命令?

3 个答案:

答案 0 :(得分:2)

如果要使用色彩映射,可以为colors列表中的每个唯一条目创建一个图例条目,如下所示。这种方法适用于任何数量的值。图例句柄是plot的标记,因此它们与散点图匹配。

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()

enter image description here

答案 1 :(得分:1)

只是一句话,不能完全回答问题:

如果使用“ seaborn”,那将是一行:

import seaborn as sns 
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"]
ax = sns.scatterplot(x=x_values, y=y_values, hue=labels)

enter image description here

PS

但是问题是关于matplotlib的。 我们在上面有答案,也可以看看: https://matplotlib.org/3.1.1/gallery/lines_bars_and_markers/scatter_with_legend.html 小节:“自动创建图例”。

但是,我觉得将这些示例修改为所需的内容并不容易。

答案 2 :(得分:0)

您可以按照以下方式制作自己的图例:

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches

x_values = [6.2, 3.6, 7.3, 3.2, 2.7]
y_values = [1.5, 3.2, 5.4, 3.1, 2.8]

a = 'red'
b = 'blue'
c = 'yellow'

colours = [a, a, b, a, c]
labels = ["a", "a", "b", "a", "c"]

axis = plt.gca()
axis.scatter(x_values, y_values, c=colours)

# Create a legend
handles = [mpatches.Patch(color=colour, label=label) for label, colour in [('a', a), ('b', b), ('c', c)]]
plt.legend(handles=handles, loc=2, frameon=True)

plt.show()

看起来像是:

plot with legend