根据类标签的 Matplotlib 颜色 [英] Matplotlib color according to class labels

查看:84
本文介绍了根据类标签的 Matplotlib 颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个向量,一个带有值,另一个带有类标签,例如1,2,3等.

我想将属于第 1 类的所有点绘制为红色,绘制为蓝色的第 2 类,绘制为绿色的第 3 类等.我该怎么做?

解决方案

已接受的答案已经说明了这一点,但如果您可能想要指定应将哪个类标签分配给特定颜色或标签,您可以执行以下操作.我用颜色条做了一些标签体操,但让情节本身减少到一个很好的单行.这对于绘制sklearn进行分类的结果非常有用.每个标签匹配一个 (x,y) 坐标.

  import matplotlib导入matplotlib.pyplot作为plt将numpy导入为npx = [4,8,12,16,1,4,9,16]y = [1,4,9,16,4,8,12,3]标签 = [0,1,2,3,0,1,2,3]颜色 = ['红色','绿色','蓝色','紫色']无花果= plt.figure(figsize =(8,8))plt.scatter(x,y,c = label,cmap = matplotlib.colors.ListedColormap(colors))cb = plt.colorbar()loc = np.arange(0,max(label),max(label)/float(len(colors)))cb.set_ticks(loc)cb.set_ticklabels(颜色)

使用

I have two vectors, one with values and one with class labels like 1,2,3 etc.

I would like to plot all the points that belong to class 1 in red, to class 2 in blue, to class 3 in green etc. How can I do that?

解决方案

The accepted answer has it spot on, but if you might want to specify which class label should be assigned to a specific color or label you could do the following. I did a little label gymnastics with the colorbar, but making the plot itself reduces to a nice one-liner. This works great for plotting the results from classifications done with sklearn. Each label matches a (x,y) coordinate.

import matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = [4,8,12,16,1,4,9,16]
y = [1,4,9,16,4,8,12,3]
label = [0,1,2,3,0,1,2,3]
colors = ['red','green','blue','purple']

fig = plt.figure(figsize=(8,8))
plt.scatter(x, y, c=label, cmap=matplotlib.colors.ListedColormap(colors))

cb = plt.colorbar()
loc = np.arange(0,max(label),max(label)/float(len(colors)))
cb.set_ticks(loc)
cb.set_ticklabels(colors)

Using a slightly modified version of this answer, one can generalise the above for N colors as follows:

import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

N = 23 # Number of labels

# setup the plot
fig, ax = plt.subplots(1,1, figsize=(6,6))
# define the data
x = np.random.rand(1000)
y = np.random.rand(1000)
tag = np.random.randint(0,N,1000) # Tag each point with a corresponding label    

# define the colormap
cmap = plt.cm.jet
# extract all colors from the .jet map
cmaplist = [cmap(i) for i in range(cmap.N)]
# create the new map
cmap = cmap.from_list('Custom cmap', cmaplist, cmap.N)

# define the bins and normalize
bounds = np.linspace(0,N,N+1)
norm = mpl.colors.BoundaryNorm(bounds, cmap.N)

# make the scatter
scat = ax.scatter(x,y,c=tag,s=np.random.randint(100,500,N),cmap=cmap,     norm=norm)
# create the colorbar
cb = plt.colorbar(scat, spacing='proportional',ticks=bounds)
cb.set_label('Custom cbar')
ax.set_title('Discrete color mappings')
plt.show()

Which gives:

这篇关于根据类标签的 Matplotlib 颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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