在离散颜色条中对齐颜色字段和标签

时间:2013-09-02 23:31:47

标签: python matplotlib boundary colorbar

我正在尝试创建一个具有离散轮廓水平的填充等高线图,我需要对其进行控制,以便比较来自不同数据源的值。我认为这应该可以通过fig.colorbar(c, ax=ax, ticks=my_levels)轻松完成。但是,正如您从下面的示例中看到的那样,颜色和值的对齐出现了问题,我无法弄清楚代码的错误。

Example for mis-aligned colors in colorbar

以下是代码:

# -*- coding: cp1252 -*-
import matplotlib
import matplotlib.pyplot as plt
from matplotlib.ticker import ScalarFormatter
import numpy as np

def plot_discrete(x, y, data, cmax, nclevel=11):
    """Plot filled contour plot and add colorbar with discrete (linear) spacing"""
    matplotlib.rcParams.update({'font.size' : 22})
    # prepare plot
    fig = plt.figure(figsize=(10,7), dpi=150)
    fig.suptitle(unicode("Test ÄÖÜßäöü","latin-1"), fontsize=20, fontweight='bold')
    ax = fig.add_subplot(1,1,1)
    # determine contour levels and set color scale (norm)
    clevel = np.linspace(0., cmax, nclevel)
    print "clevel = ", clevel
    print "cmax, max(data) = ", cmax, np.max(data)
    norm = matplotlib.colors.BoundaryNorm(clevel, ncolors=256, clip=False)
    # generate the contour plot
    c = ax.contourf(x, y, data, level=clevel, norm=norm)
    # prep up axis formatting and labelling
    ax.set_xlabel('X',{'fontsize':20})
    ax.set_ylabel('Y',{'fontsize':20})
    ax.xaxis.set_major_formatter(ScalarFormatter())
    ax.yaxis.set_major_formatter(ScalarFormatter())
    # add the colorbar
    fig.colorbar(c, ax=ax, norm=norm, ticks=clevel, boundaries=clevel)
    plt.show()


if __name__ == "__main__":
    x = np.linspace(0.,10.,20)
    y = np.linspace(-10.,10.,21)
    data = np.zeros((x.size, y.size))
    for i,xx in enumerate(x):
        for j,yy in enumerate(y):
            data[i,j] = np.sqrt(xx)*yy**2
    plot_discrete(y, x, data, 360.)

1 个答案:

答案 0 :(得分:1)

经过一番挖掘后,我相信我已经发现了你的问题:

该行

c = ax.contourf(x, y, data, level=clevel, norm=norm)

应该{​​{1}}为level,这意味着它现在可以看到正确的参数并使用您用户定义的级别!