Search code examples
pythonnumpymatplotliblabelcontourf

How can I change the scale labels in matplotlibs contourf method?


I have created the image

enter image description here

using the following code:

import matplotlib.pyplot as plt


def build_contour_plot(nu):
    plt.contourf(B, D, nu, 111)
    plt.colorbar()
    plt.xlabel('X')
    plt.ylabel('Y')
    plt.show()


b = np.arange(0, 1.0, 0.001)
d = np.arange(0, 1.0, 0.001)
B, D = np.meshgrid(b, d)
nu = np.ceil(np.minimum(B, D)*5)/5
build_contour_plot(nu)

How can I make the labels on the scale on the right-hand-side to be [0, 0.1, 0.2, ..., 1] instead of [0.00, 0.11, ..., 0.99]?


Solution

  • The ticks parameter of colorbar accepts a list of ticks, or a Locator such as MultipleLocator:

    import matplotlib.ticker as mticker
    
    def build_contour_plot(nu):
        plt.contourf(B, D, nu, 111)
        plt.colorbar(ticks=mticker.MultipleLocator(0.1))
        plt.xlabel('X')
        plt.ylabel('Y')
        plt.show()
    

    Output:

    enter image description here