• Set the figure size and adjust the padding between and around the subplots.
  • Initialize a variable,N, for number ">

    How to plot contourf and log color scale in Matplotlib?



    To plot contourf and log scale in Matplotlib, we can take the following steps −

    • Set the figure size and adjust the padding between and around the subplots.
    • Initialize a variable,N, for number of sample data.
    • Create x, y, X, Y, Z1, Z2 and z data points using numpy.
    • Create a figure and a set of subplots.
    • Plot contours using contourf() method.
    • Create a colorbar for a scalar mappable instance.
    • To display the figure, use show() method.

    Example

    import matplotlib.pyplot as plt
    import numpy as np
    from numpy import ma
    from matplotlib import ticker, cm
    
    plt.rcParams["figure.figsize"] = [7.50, 3.50]
    plt.rcParams["figure.autolayout"] = True
    
    N = 100
    x = np.linspace(-3.0, 3.0, N)
    y = np.linspace(-2.0, 2.0, N)
    
    X, Y = np.meshgrid(x, y)
    
    Z1 = np.exp(-X**2 - Y**2)
    Z2 = np.exp(-(X * 10)**2 - (Y * 10)**2)
    
    z = Z1 + 50 * Z2
    z[:5, :5] = -1
    z = ma.masked_where(z <= 0, z)
    fig, ax = plt.subplots()
    
    cs = ax.contourf(X, Y, z, locator=ticker.LogLocator(), cmap=cm.PuBu_r)
    cbar = fig.colorbar(cs)
    
    plt.show()

    Output

    Kickstart Your Career

    Get certified by completing the course

    Get Started
    Advertisements