Search code examples
pythonmatplotlibcolorbarcolormapnormalize

BoundaryNorm, unexpected behavior


My code:

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

x = y = np.linspace(0, 10, 51)
X, Y = np.meshgrid(x, y)
Z = X+Y # Z.min() => 0, Z.max() => 20 
cf = plt.contourf(X, Y, Z,
                  levels=[5, 10, 15],
                  norm=colors.BoundaryNorm([5, 10, 15], 256, extend='both'))
cb = plt.colorbar(cf, extend='both')
plt.show()

Its output:

enter image description here

My expectations:

  • in the main plot, a dark blue lower triangle in place of the white one,
  • ditto, a bright yellow upper triangle,
  • the colorbar decorated with an upper bright yellow triangle and a lower dark blue triangle.

My question:

What have I done wrong?


Solution

  • As @JohanC notes, colorbar does strange things with a contour. However, in this simple case, why are you using BoundaryNorm?

    import numpy as np
    import matplotlib.pyplot as plt
    from matplotlib import colors
    
    x = y = np.linspace(0, 10, 51)
    X, Y = np.meshgrid(x, y)
    Z = X+Y # Z.min() => 0, Z.max() => 20
    cf = plt.contourf(X, Y, Z,
                      levels=[5, 10, 15], extend='both')
    cb = plt.colorbar(cf, extend='both')
    plt.show()
    

    Does exactly what you want.

    enter image description here