Python pyplot图例散点图 [英] Python pyplot legend scatter

查看:66
本文介绍了Python pyplot图例散点图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 5 个类和一些要绘制的功能.这是代码

x_pts = X_test.iloc[:,col_1]y_pts = X_test.iloc[:,col_2]color_seq = y_testplt.scatter(x_pts,y_pts,c = color_seq,cmap ='viridis')plt.xlabel(X_test.columns[col_1])plt.ylabel(X_test.columns[col_2])plt.show()

这将导致下图

我现在想要每种颜色的图例(例如,黄色 = 'class a',蓝色 = 'class b',...)我能找到的唯一文档是人们以不同的方式绘制每种颜色,这在我的具体情况下非常困难.没有一种简单的方法来显示图例

I've got 5 classes and some features that I want to plot. This is the code

x_pts = X_test.iloc[:,col_1]
y_pts = X_test.iloc[:,col_2]
color_seq = y_test
plt.scatter(x_pts, y_pts, c=color_seq, cmap='viridis')
plt.xlabel(X_test.columns[col_1])
plt.ylabel(X_test.columns[col_2])
plt.show()

and this results in the following image

I now want a legend for each color (e.g. yellow = 'class a' , blue = 'class b', ...) The only documentation I can find is of people plotting each color differently, which is quite hard in my specific case. Isn't there a simple way to display a legend like the example here

解决方案

Hope this helps:

x = [1, 3, 4, 6, 7, 9]
y = [0, 0, 5, 8, 8, 8]
labels = ['A', 'B', 'C']
colors = [0, 0, 1, 2, 2, 2]
scatter = plt.scatter(x, y,c=colors, cmap='viridis')
plt.legend(handles=scatter.legend_elements()[0], labels=labels)
plt.show()

Output:

这篇关于Python pyplot图例散点图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆