我想为一个imshow图合并两个颜色映射。我想使用'RdBu'范围为-0.4到0.4,然后从0.4到最大值(比如说1.5),我想使用从相同的蓝色到另一种颜色(例如绿色)的渐变。在matplotlib中合并颜色映射
我该怎么做?
这是多远我走到这一步:
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.colors as colors
from matplotlib.mlab import bivariate_normal
N = 100
'''
Custom Norm: An example with a customized normalization. This one
uses the example above, and normalizes the negative data differently
from the positive.
'''
X, Y = np.mgrid[-3:3:complex(0, N), -2:2:complex(0, N)]
Z1 = (bivariate_normal(X, Y, 1., 1., 1.0, 1.0))**2 \
- 0.4 * (bivariate_normal(X, Y, 1.0, 1.0, -1.0, 0.0))**2
Z1 = Z1/0.03
# Example of making your own norm. Also see matplotlib.colors.
# From Joe Kington: This one gives two different linear ramps:
class MidpointNormalize(colors.Normalize):
def __init__(self, vmin=None, vmax=None, midpoint=None, clip=False):
self.midpoint = midpoint
colors.Normalize.__init__(self, vmin, vmax, clip)
def __call__(self, value, clip=None):
# I'm ignoring masked values and all kinds of edge cases to make a
# simple example...
x, y = [self.vmin, self.midpoint, self.vmax], [0, 0.5, 1]
return np.ma.masked_array(np.interp(value, x, y))
fig, ax = plt.subplots(1, 1)
minValue = Z1.min()
maxValue = 0.4
pcm = ax.imshow(Z1,
norm=MidpointNormalize(midpoint=0.),
vmin=minValue, vmax=maxValue,
cmap='RdBu',
origin='lower',
aspect=1.0,
interpolation='none')
cbar = fig.colorbar(pcm, ax=ax, extend='both', ticks=[minValue, 0.0, maxValue])
fig.tight_layout()
plt.show()
这解决了我的问题。我喜欢这个解决方案,因为它很容易通用,可以合并任何颜色映射,也可以在颜色映射中添加任意数量的段。谢谢! – fromGiants