2017-09-22 22 views
2

我的目標是是使用通過字典,一個給定的數字的給定顏色對應一個顏色表。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

回答

2

如果指定的顏色數(在你的情況[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

3

一個顏色表始終是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