matplotlib:不进行规范化的dict颜色

2024-07-08 08:33:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我的目标是使用一个颜色映射图,它通过dict将给定的数字映射到给定的颜色。在

然而,matplotlib似乎已经将标准化了数字。在

例如,我首先创建了一个自定义颜色映射use 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

^{pr2}$

但是,它给了我颜色['pumpkin', 'salmon', 'pale grey']

scatter

简而言之: 颜色图

palette

正在获取颜色0、1和2(所需的):

enter image description here

但是matplotlib给出了:

enter image description here


Tags: 目标matplotlib颜色useplt数字seaborndict
2条回答

颜色贴图始终在0和1之间规格化。散点图默认情况下将规范化给c参数的值,以便colormap的范围从最小值到最大值。但是,您当然可以定义自己的规范化。在本例中,它将是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

如果将颜色指定为数字序列(在您的例子中是[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

相关问题 更多 >

    热门问题