matplotlib:颜色由字典不归

问题描述:

我的目标是是使用通过字典,一个给定的数字的给定颜色对应一个颜色表。matplotlib:颜色由字典不归

然而,matplotlib似乎有归一化的数量。

例如,我首先创建一个自定义颜色表使用seaborn,并反馈到plt.scatter

import seaborn as sns 

colors = ['pumpkin', "bright sky blue", 'light green', 'salmon', 'grey', 'pale grey'] 
pal = sns.xkcd_palette(colors) 
sns.palplot(pal) 

palette

from matplotlib import pyplot as plt 
from matplotlib.colors import ListedColormap 

cmap = ListedColormap(pal.as_hex()) 
x = [0, 1, 2] 
y = [0, 1, 2] 
plt.scatter(x, y, c=[0, 1, 2], s=500, cmap=cmap) # I'd like to get color ['pumpkin', "bright sky blue", 'light green'] 

,但是,它给我颜色

scatter

简而言之: 颜色映射

palette

得到颜色0,1和2(期望):

enter image description here

matplotlib给出:

enter image description here

如果指定的颜色数(在你的情况[0,1,2])的序列,那么这些数字将被映射到使用标准化的颜色。您可以代替直接指定颜色序列:

x = [0, 1, 2] 
y = [0, 1, 2] 
clrs = [0, 1, 2] 
plt.scatter(x, y, c=[pal[c] for c in clrs], s=500) 

enter image description here

一个颜色表始终是0和1之间标准化散点图将默认正常化给予c值参数,使得色彩图的范围从最小值到最大值。但是,你当然可以定义你自己的规范化。在这种情况下,它将是vmin=0, vmax=len(colors)

from matplotlib import pyplot as plt 
from matplotlib.colors import ListedColormap 

colors = ['xkcd:pumpkin', "xkcd:bright sky blue", 'xkcd:light green', 
      'salmon', 'grey', 'xkcd:pale grey'] 
cmap = ListedColormap(colors) 

x = range(3) 
y = range(3) 
plt.scatter(x, y, c=range(3), s=500, cmap=cmap, vmin=0, vmax=len(colors)) 

plt.show() 

enter image description here