Search code examples
pythonpython-3.xmatplotlibsubplotaxes

Getting ticks on same horizontal grid for plots with different scale


This site describes well how to draw two lines with different scales on the same plot. However, the y ticks are not aligned as you can see in the following picture if I draw an horizontal grid across. enter image description here

Is there a way to add ticks so that they align (e.g. the 5000 on the left is aligned with the 0.50 on the right, etc.)?


Solution

  • One could align the right ticks by setting their ylims to the corresponding ylims of the left:

    ymin1, ymax1 = ax1.get_ylim()
    ax2.set_ylim(ymin1 / 10000, ymax1 / 10000)
    

    Or set the ylims of both axes to the widest range:

    import numpy as np
    import matplotlib.pyplot as plt
    
    # Create some mock data
    t = np.arange(0.01, 10.0, 0.01)
    data1 = np.exp(t)
    data2 = np.sin(2 * np.pi * t)
    
    fig, ax1 = plt.subplots()
    
    color = 'tab:red'
    ax1.set_xlabel('time (s)')
    ax1.set_ylabel('exp', color=color)
    ax1.plot(t, data1, color=color)
    ax1.tick_params(axis='y', labelcolor=color)
    
    ax2 = ax1.twinx()  # instantiate a second axes that shares the same x-axis
    
    color = 'tab:blue'
    ax2.set_ylabel('sin', color=color)  # we already handled the x-label with ax1
    ax2.plot(t, data2, color=color)
    ax2.tick_params(axis='y', labelcolor=color)
    
    ymin1, ymax1 = ax1.get_ylim()
    ymin2, ymax2 = ax2.get_ylim()
    ymin1 = min(ymin1, ymin2 * 10000)
    ymax1 = max(ymax1, ymax2 * 10000)
    ax1.set_ylim(ymin1, ymax1)
    ax2.set_ylim(ymin1 / 10000, ymax1 / 10000)
    
    ax1.grid(True, axis='y')
    fig.tight_layout()  # otherwise the right y-label is slightly clipped
    plt.show()
    

    result