我的整数范围从0到10000.我想将颜色映射到每个.然后基于整数值我想要检索相当于整数值的RGB等效颜色.基本上我想要在两种或更多种颜色之间具有插值效果,例如,如果颜色是绿色和红色,则绿色具有最小权重(0)并且红色具有最高权重(10000).我如何使用matplotlib实现此映射,或者是否有任何其他库相同.
确实可以从给定的colormap中采样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")
Run Code Online (Sandbox Code Playgroud)
结果:

编辑
还可以添加一个颜色栏:
#!/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")
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3181 次 |
| 最近记录: |