python - Matplotlib 颜色根据类标签

标签 python matplotlib

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

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

最佳答案

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

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)

Scatter plot color labels

使用稍作修改的 this答案,可以将上述 N 种颜色概括如下:

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

这给出了:

enter image description here

关于python - Matplotlib 颜色根据类标签,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12487060/

相关文章:

python - pandas DataFrame.to_sql 和 nan 值

python - DNA 序列点图

python - 即使在清除之后,图形仍然不断增长

python - 将辅助数据绘制为第二个 y 轴上的刻度

python - 试图理解 Python 中的抽象工厂模式

python - 在Maya中,使用Python或Mel,如何查找没有UV壳的对象

python - 运行 Python 程序时出现问题,错误 : Name 's' is not defined

python - 一行散点图标签 - Matplotlib

python - 在一系列时间索引上绘制 DataFrame

python - 使用 NAN 替换强制转换非数字 numpy 数组