Search code examples
matplotlibcolorbar

Draw colorbar with twin scales


I'd like to draw a (vertical) colorbar, which has two different scales (corresponding to two different units for the same quantity) on each side. Think Fahrenheit on one side and Celsius on the other side. Obviously, I'd need to specify the ticks for each side individually.

Any idea how I can do this?


Solution

  • That should get you started:

    import matplotlib.pyplot as plt
    import numpy as np
    
    # generate random data
    x = np.random.randint(0,200,(10,10))
    plt.pcolormesh(x)
    
    # create the colorbar
    # the aspect of the colorbar is set to 'equal', we have to set it to 'auto',
    # otherwise twinx() will do weird stuff.
    cbar = plt.colorbar()
    pos = cbar.ax.get_position()
    cbar.ax.set_aspect('auto')
    
    # create a second axes instance and set the limits you need
    ax2 = cbar.ax.twinx()
    ax2.set_ylim([-2,1])
    
    # resize the colorbar (otherwise it overlays the plot)
    pos.x0 +=0.05
    cbar.ax.set_position(pos)
    ax2.set_position(pos)
    
    plt.show()
    

    enter image description here