pythonmatplotlibplotseaborn

How do I align gridlines for two y-axis scales?


I'm plotting two datasets with different units on the y-axis. Is there a way to make the ticks and gridlines aligned on both y-axes?

The first image shows what I get, and the second image shows what I would like to get.

This is the code I'm using to plot:

import seaborn as sns
import numpy as np
import pandas as pd

np.random.seed(0)
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(pd.Series(np.random.uniform(0, 1, size=10)))
ax2 = ax1.twinx()
ax2.plot(pd.Series(np.random.uniform(10, 20, size=10)), color='r')

Example of unwanted behavior

Example of wanted behavior


Solution

  • I am not sure if this is the prettiest way to do it, but it does fix it with one line:

    import matplotlib.pyplot as plt
    import seaborn as sns
    import numpy as np
    import pandas as pd
    
    np.random.seed(0)
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax1.plot(pd.Series(np.random.uniform(0, 1, size=10)))
    ax2 = ax1.twinx()
    ax2.plot(pd.Series(np.random.uniform(10, 20, size=10)), color='r')
    
    # ADD THIS LINE
    ax2.set_yticks(np.linspace(ax2.get_yticks()[0], ax2.get_yticks()[-1], len(ax1.get_yticks())))
    
    plt.show()