根据列中的值使用matplotlib生成图例

时间:2019-07-17 11:40:53

标签: matplotlib legend

假设我们在2个不同的测试中有一个4个人得分的数据框,并且第3列告诉我们他们总体上通过还是未通过

df:

[10,20,failed
 10,40,passed
 20,40,passed
 30,10,failed]

我想生成一个散点图,在x轴上显示第一列的分数,在y轴上显示第二个测试的分数,并用颜色(或标记)指示它们是否通过。我已经做到了:

plt.scatter(x=df[column1], y=df[column2], c=df[column3])

问题是,如何根据颜色(或标记)和column3创建图例?

[red: failed
 blue: passed]

1 个答案:

答案 0 :(得分:0)

这是我的建议:分别对失败的通过者进行绘图,以获取其句柄,然后将其用于图例。

fig = plt.figure()
ax1 = fig.add_subplot(111)

passed = ax1.scatter(x=df.loc[df[column3].eq('passed'), column1], y=df.loc[df[column3].eq('passed'), column2], c='green')
failed = ax1.scatter(x=df.loc[df[column3].eq('failed'), column1], y=df.loc[df[column3].eq('failed'), column2], c='red')

ax1.legend(handles=[passed, failed], labels=['Passed', 'Failed'])