Search code examples
pythonmatplotlibcontourf

contourf is not reflecting ListedColormap with boundaries


Is possible to apply custom colorbar with boundaries to graph? For example to contourf?

Because I can change boundaries of colorbar, but contourf is not reflecting these boundaries.

colors = ["#ffffff", "#FFD8CA", "#FFAB98", "#FF7765", "#FF3E33", "#FF0000"]
cmap = matplotlib.colors.ListedColormap(colors)

m = plt.cm.ScalarMappable(cmap=cmap)
m.set_array(zi)
m.set_clim(min(z), max(z))
plt.colorbar(m, boundaries=[min(z), 0.35, 0.7, 1.05, 1.4, min(z)])
plt.contourf(xi, yi, zi, 6, cmap=cmap,alpha=0.7, vmin=min(z), vmax=max(z))

Solution

  • If you have 6 boundary values, you need 5 colors.
    The boundaries are the levels of your contour. Specify this via the levels argument. Then the colorbar will automatically be correct.

    import numpy as np
    import matplotlib.pyplot as plt
    import matplotlib.colors
    
    x,y = np.meshgrid(np.linspace(-3,3), np.linspace(-3,3))
    z = np.exp(-x**2-y**2)*1.5+0.2
    
    colors = ["white", "mistyrose", "lightcoral", "firebrick", "black"]
    cmap= matplotlib.colors.ListedColormap(colors)
    boundaries=[z.min(), 0.35, 0.7, 1.05, 1.4, z.max()]
    
    m = plt.contourf(x, y, z, levels = boundaries, cmap=cmap)
    
    plt.colorbar(m, spacing="proportional")
    plt.show()
    

    enter image description here