我的整数范围从0到10000.我想将颜色映射到每个。然后基于整数值我想要检索RGB等效于整数值的颜色。基本上我想要在两种或更多种颜色之间具有插值效果,例如如果颜色是绿色和红色,则绿色具有最小重量(0),红色具有最高重量(10000)。我如何使用matplotlib实现此映射,或者是否有任何其他库。
答案 0 :(得分:6)
确实可以从给定的色彩图中采样10000种颜色:
#!/usr/bin/python3
from numpy import arange
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib.colors import LinearSegmentedColormap
# ======
## data:
N = 10000
data = arange(N +1)
# =================
## custom colormap:
# red-green colormap:
cdict = {'red': [(0.0, 1.0, 1.0), # red decreases
(1.0, 0.0, 0.0)],
'green': [(0.0, 0.0, 0.0), # green increases
(1.0, 1.0, 1.0)],
'blue': [(0.0, 0.0, 0.0), # no blue at all
(1.0, 0.0, 0.0)]}
red_green_cm = LinearSegmentedColormap('RedGreen', cdict, N)
# ======
## plot:
colors = cm.get_cmap(red_green_cm, N)
fig = plt.figure()
ax = fig.add_subplot(111)
# each line is of its own color:
for i, x in enumerate(data):
ax.plot(data, data*x, color=colors(i))
fig.savefig("red-green-cm.png")
结果:
修改强>
还可以添加颜色栏:
#!/usr/bin/python3
from numpy import arange
import matplotlib as mpl
from matplotlib import pyplot as plt
from matplotlib import cm
from matplotlib.colors import LinearSegmentedColormap
# ======
## data:
N = 10000
data = arange(N +1)
# =================
## custom colormap:
# red-green colormap:
cdict = {'red': [(0.0, 1.0, 1.0), # red decreases
(1.0, 0.0, 0.0)],
'green': [(0.0, 0.0, 0.0), # green increases
(1.0, 1.0, 1.0)],
'blue': [(0.0, 0.0, 0.0), # no blue at all
(1.0, 0.0, 0.0)] }
red_green_cm = LinearSegmentedColormap('RedGreen', cdict, N)
# ======
## plot:
colors = cm.get_cmap(red_green_cm, N)
fig = plt.figure()
ax = fig.add_subplot(111)
# each line is of its own color:
for i, x in enumerate(data):
ax.plot(data, data*x, color=colors(i))
# make space for colorbar:
fig.tight_layout(rect=[0, 0, 0.85, 1])
# adding colorbar:
ax_cb = fig.add_axes([0.85, 0.10, 0.05, 0.8])
norm = mpl.colors.Normalize(vmin=data[0], vmax=data[-1])
cb = mpl.colorbar.ColorbarBase(ax_cb, cmap=red_green_cm, norm=norm, orientation='vertical')
fig.savefig("red-green-cm.png")
答案 1 :(得分:0)
范围介于两个极端之间的色彩映射称为Diverging,matplotlib中的RdYlGn(红 - 黄 - 绿)色彩映射完全符合您的要求。看看colormaps reference。我不知道范围是0到10,000,虽然它肯定会处理0到100,你可以将你的范围映射到它。