是否可以定义一个在两个给定颜色之间进行对数插值的 matplitlib 颜色图?
背景:当通过 imshow(...) 命令在 matplotlib 中绘制数组时,colormaps 用于为每个数组分配颜色数据值。通常,使用 matplotlib.cm 中的预定义颜色图,但也可以使用 matplotlib.colors.LinearSegmentedColormap 创建更多增强的颜色图。 通常,在这些颜色图中,颜色值随数据值线性变化。
提示:我的问题是不是,如何以对数方式绘制数组。这通常是通过保持线性颜色图和一些技巧(通过绘制 log(array) 并将颜色栏上的标签 x 替换为 10^x ,或通过显式更改 plot 命令的规范化行为)。在这里,我明确需要颜色图实例。
请您参考如下方法:
您可以提供一个假的 Colormap 来应用您想要的规范化,然后再将其传递给真实的颜色图。这是这样一个颜色图实现:
import matplotlib as mpl
class ReNormColormapAdaptor(mpl.colors.Colormap):
""" Colormap adaptor that uses another Normalize instance
for the colormap than applied to the mappable. """
def __init__(self,base,cmap_norm,orig_norm=None):
if orig_norm is None:
if isinstance(base,mpl.cm.ScalarMappable):
orig_norm = base.norm
base = base.cmap
else:
orig_norm = mpl.colors.Normalize(0,1)
self._base = base
if (
isinstance(cmap_norm,type(mpl.colors.Normalize))
and issubclass(cmap_norm,mpl.colors.Normalize)
):
# a class was provided instead of an instance. create an instance
# with the same limits.
cmap_norm = cmap_norm(orig_norm.vmin,orig_norm.vmax)
self._cmap_norm = cmap_norm
self._orig_norm = orig_norm
def __call__(self, X, **kwargs):
""" Re-normalise the values before applying the colormap. """
return self._base(self._cmap_norm(self._orig_norm.inverse(X)),**kwargs)
def __getattr__(self,attr):
""" Any other attribute, we simply dispatch to the underlying cmap. """
return getattr(self._base,attr)
因为它获得的值已经被归一化为 [0,1),它需要知道之前的归一化来撤销它(给定为 orig_norm)。如果要将颜色图应用于非标准化值,请将其留空:
cmap = ReNormColormapAdaptor(mpl.cm.jet,mpl.colors.LogNorm(vmin,vmax))
如果您已经有一个ScalarMappable,那么您可以传递它而不是颜色图,颜色图、先前的归一化和新的归一化限制都将从那里获取:
import matplotlib.pyplot as plt
scalar_mappable = plt.imshow(C);
scalar_mappable.set_cmap(ReNormColormapAdaptor(
scalar_mappable,
mpl.colors.LogNorm
))
