使用plt.colorbar()时在matplotlib中定义自定义规范化函数

时间:2016-02-09 14:52:11

标签: python matplotlib colors

要使用matplotlib颜色条,必须使用matplotlib.cm.ScalarMappable的子类中的对象指定matplotlib.colors.Normalizecolorbar可以从中知道如何将数据规范化为[0, 1]浮动值。

matplotlib,线性归一化,日志,幂律等提供的归一化过程很少,但在实践中,我们可能想要使用自己编写的其他归一化函数。

我们可以使用任何函数将数据数组规范化为[0,1],但如果没有Scalarmappable使用Nomalization子类构建,则颜色条不会有正确的标记和标签。

我想知道我对matplotlib colorbar的理解是对吗还是有其他方法可以很容易地做到这一点?或者我们必须手动编写一个子类来包装自定义规范化函数?

2 个答案:

答案 0 :(得分:1)

为此,您可以轻松地将matplotlib.colors.Normalize子类化。这是我为previous SO question编写的分段规范化类的示例:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import Normalize

class PiecewiseNorm(Normalize):
    def __init__(self, levels, clip=False):
        # input levels
        self._levels = np.sort(levels)
        # corresponding normalized values between 0 and 1
        self._normed = np.linspace(0, 1, len(levels))
        Normalize.__init__(self, None, None, clip)

    def __call__(self, value, clip=None):
        # linearly interpolate to get the normalized value
        return np.ma.masked_array(np.interp(value, self._levels, self._normed))

    def inverse(self, value):
        return 1.0 - self.__call__(value)

例如:

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

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

fig, ax = plt.subplots(2, 2, gridspec_kw={'width_ratios':(20, 1), 'wspace':0.05})

im0 = ax[0, 0].contourf(x, y, H, levels, cmap='jet', norm=PiecewiseNorm(levels))
cb0 = fig.colorbar(im0, cax=ax[0, 1])
im1 = ax[1, 0].contourf(x, y, H1, levels1, cmap='jet', norm=PiecewiseNorm(levels1))
cb1 = fig.colorbar(im1, cax=ax[1, 1])

plt.show()

enter image description here

答案 1 :(得分:0)

感谢@ali_m的想法,几天之后我想我想到了用任何规范化函数 keep <- function(x, name) {assign(as.character(substitute(name)), x, pos = 1)} iris %>% ddply(.(Species), summarise, mean.petal = mean(Petal.Length), mean.sepal = mean(Sepal.Length)) %>% keep(unsorted.data) %>% # keep this step arrange(mean.petal) %>% {.} -> sorted.data sorted.data # Species mean.petal mean.sepal #1 setosa 1.462 5.006 #2 versicolor 4.260 5.936 #3 virginica 5.552 6.588 unsorted.data # Species mean.petal mean.sepal #1 setosa 1.462 5.006 #2 versicolor 4.260 5.936 #3 virginica 5.552 6.588 定义自定义Normalization子类。基本上用任何y=func(x)给出的规范化值替换私有成员self._normed。在初始化子类时,必须将函数钩子赋予规范化函数func(self._levels)。但请确保func必须是真正的规范化。

以下代码的灵感来自@ali_m的答案:

func
相关问题