[Python] Colorbar does not match contour graph

Discussão em 'Python' iniciado por Stack, Agosto 22, 2025.

  1. Stack

    Stack Membro Participativo

    I want to make a contour plot with only 2 colors: Blue if the value is below a threshold, red if it's above. I've also added a colorbar for more clarity. Here's the code portion, I have voluntarily simplified it for this post:

    from matplotlib import colors, cm
    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.tri as tri

    np.random.seed(19680801)
    npts = 200
    ngridx = 100
    ngridy = 200
    x = np.random.uniform(-2, 2, npts)
    y = np.random.uniform(-2, 2, npts)
    z = x * np.exp(-x**2 - y**2)

    xi = np.linspace(-2.1, 2.1, ngridx)
    yi = np.linspace(-2.1, 2.1, ngridy)

    triang = tri.Triangulation(x, y)
    interpolator = tri.LinearTriInterpolator(triang, z)

    Xi, Yi = np.meshgrid(xi, yi)
    zi = interpolator(Xi, Yi)

    fig = plt.figure()
    ax = fig.subplots()

    colormapList = ['blue', 'red']
    colorThreshold = np.mean(z)

    norm = colors.BoundaryNorm([colorThreshold-1e-3, colorThreshold], ncolors = 2, clip = True)
    cmap = colors.LinearSegmentedColormap.from_list('name', colormapList, N = 2)

    ax.contour(xi, yi, zi, norm = norm, cmap = cmap)

    mappable = cm.ScalarMappable(norm = norm, cmap = cmap)

    cbar = fig.colorbar(mappable, ax = ax)
    cbar.set_ticks([np.min(zi), colorThreshold, np.max(zi)])
    cbar.set_ticklabels([np.min(zi), colorThreshold, np.max(zi)])


    The issue I have is that the colorbar should show blue below the threshold and red above the threshold , but it shows white and blue below the threshold, then white above the threshold. For some reason, it also shows a 4th unnamed tick when I only ask for 3 ticks. Here's an example:

    [​IMG]

    What am I missing?

    Continue reading...

Compartilhe esta Página