matplotlib:按字典着色,无需标准化 [英] matplotlib: color by dict without normalization
问题描述
我的目标是使用通过字典将给定数字映射到给定颜色的颜色图.
My goal is is to use a colormap that maps via a dict, a given number to a given color.
然而,matplotlib 似乎已经规范化了这个数字.
However, matplotlib seems to have normalized the number.
例如,我首先使用seaborn
创建了一个自定义颜色图,并将其输入到plt.scatter
For example, I first created a custom colormap use seaborn
, and feed it into 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)
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']
但是,它给了我颜色 ['pumpkin', 'salmon', 'pale grey']
简而言之:颜色图:
获取颜色 0、1 和 2(期望):
getting color 0, 1, and 2 (desired):
但 matplotlib
给出:
推荐答案
颜色图始终在0到1之间进行归一化.散布图默认情况下会归一化为 c
参数提供的值,例如颜色图的范围从最小值到最大值.但是,您当然可以定义自己的规范化.在这种情况下,它应该是 vmin = 0,vmax = len(colors)
.
A colormap is always normalized between 0 and 1. A scatter plot will by default normalize the values given to the c
argument, such that the colormap ranges from the minimum to the maximum value. However, you may of course define your own normalization. In this case it would be 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()
这篇关于matplotlib:按字典着色,无需标准化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!