基于分类类在 matplotlib 图中提及标签 [英] Mention label in matplotlib plot based on categorical class

查看:36
本文介绍了基于分类类在 matplotlib 图中提及标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在地块上贴上标签.我的代码就像

 将matplotlib.pyplot导入为pltx1 = [1,2,3,4,5,6,7,8,9,10]x2 = [7,3,2,4,1,4,3,5,8,4]y = [0,1,1,0,1,0,0,1,0,1]plt.scatter(x1,x2,c = y)plt.show()

输出:

我想在图上放置图例标签 0 1 .如果 label 是 False 或 true ,那很好吗?

如果答案没有任何重复,我们将不胜感激

解决方案

原则上的问题,例如

请注意,这是一个纯粹的学术示例,使用 for 循环要容易得多.

I want to put label on plot. my code is like

import matplotlib.pyplot as plt
x1 = [1,2,3,4,5,6,7,8,9,10]
x2 = [7,3,2,4,1,4,3,5,8,4]
y  = [0,1,1,0,1,0,0,1,0,1]
plt.scatter(x1,x2,c=y)
plt.show()

Output:

I want to put legend label 0 and 1 on graph. its good if label is False or true ?

It is appreciated if answer is without any iterations

解决方案

In principle questions like matplotlib scatterplot with legend or Matplotlib scatter plot with legend show how to get a legend for a scatter plot.

Since you explicitely ask not to have iterations, you may of course replace iterations by mappings.

import matplotlib.pyplot as plt
import numpy as np

x1 = [1,2,3,4,5,6,7,8,9,10]
x2 = [7,3,2,4,1,4,3,5,8,4]
y  = [0,1,1,0,1,0,0,1,0,1]
plt.scatter(x1,x2,c=y, cmap="viridis")

yunique = np.unique(y).astype(float)
handles = list(map(lambda i: plt.plot([], 
                color=plt.cm.viridis(i),marker="o", ls="")[0], yunique))
labels = list(map(str, yunique.astype(bool)))
plt.legend(handles=handles, labels=labels)

plt.show()

Note that this is a purely academic example and it is much easier to use a for-loop.

这篇关于基于分类类在 matplotlib 图中提及标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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