Matplotlib的非线性色图

Rik*_*ike 6 python matplotlib

我有想要使用非线性色彩图用contourf/tricontourf绘制的数据.

我发现了一个脚本(见下文),只要级别介于0和正数之间,就可以为色彩图提供一个很好的解决方案.

但是,我的数据是负数(介于-50和0之间).不幸的是,根据我的情况调整水平根本不起作用(见图,子图3).那么有什么我需要考虑的吗?有没有人对我有任何建议,甚至可能遇到同样的问题?

我将衷心感谢您的帮助.

from pylab import *
from numpy import *
from matplotlib.colors import LinearSegmentedColormap

class nlcmap(LinearSegmentedColormap):
    """A nonlinear colormap"""

    name = 'nlcmap'

    def __init__(self, cmap, levels):
        self.cmap = cmap
        self.monochrome = self.cmap.monochrome
        self.levels = asarray(levels, dtype='float64')
        self._x = self.levels/ self.levels.max()
        self.levmax = self.levels.max()
        self.levmin = self.levels.min()
        self._y = linspace(self.levmin, self.levmax, len(self.levels))

    def __call__(self, xi, alpha=1.0, **kw):
        yi = interp(xi, self._x, self._y)
        return self.cmap(yi/self.levmax, alpha)

if __name__ == '__main__':

    y, x = mgrid[0.0:3.0:100j, 0.0:5.0:100j]
    H = 50.0 * exp( -(x**2 + y**2) / 4.0 )
    levels = [0, 1, 2, 3, 6, 9, 20, 50]

    H1 = -50.0 * exp( -(x**2 + y**2) / 4.0 )
    levels1 = [-50, -20, -9, -6, -3, -2, -1, 0]

    cmap_lin = cm.jet
    cmap_nonlin = nlcmap(cmap_lin, levels)
    cmap_lin1 = cm.jet
    cmap_nonlin1 = nlcmap(cmap_lin1, levels1)

    subplot(4,1,1)
    contourf(x, y, H, levels, cmap=cmap_nonlin)
    colorbar()
    subplot(4,1,2)
    contourf(x, y, H, levels, cmap=cmap_lin)
    colorbar()
    subplot(4,1,3)
    contourf(x, y, H1, levels1, cmap=cmap_nonlin1)
    colorbar()
    subplot(4,1,4)
    contourf(x, y, H1, levels1, cmap=cmap_lin1)
    colorbar()

    plt.show()  
Run Code Online (Sandbox Code Playgroud)

具有非线性色图的等高线图

tho*_*as 3

在这个例子中,levels1 = [-50, -20, -9, -6, -3, -2, -1, 0]当你说 时,你除以零self._x = self.levels/ self.levels.max()。似乎函数会pcolorcontourf将输入数据传递到颜色图之前将其重新缩放到 0 和 1 之间。因此,您还需要将级别重新调整到该范围,您的代码在第一个示例中执行此操作,但在第二个示例中则不然。这似乎有效:

class nlcmap(LinearSegmentedColormap):
    """A nonlinear colormap"""

    name = 'nlcmap'

    def __init__(self, cmap, levels):
        self.cmap = cmap
        self.monochrome = self.cmap.monochrome
        self.levels = asarray(levels, dtype='float64')
        self._x = self.levels-self.levels.min()
        self._x/= self._x.max()
        self._y = linspace(0, 1, len(self.levels))

    def __call__(self, xi, alpha=1.0, **kw):
        yi = interp(xi, self._x, self._y)
        return self.cmap(yi, alpha)
Run Code Online (Sandbox Code Playgroud)