May-17-2022, 03:31 PM
(This post was last modified: May-17-2022, 03:31 PM by deanhystad.)
This creates two subplots. It returns a figure and an axes array.
This is creating ONE additional y axis for each of your subplots.
What you did in your initial post was treat twinx() like it returned a 2nd y axis. It does not. twinx() creates a new y axis. If you call twinx() ten times it will create 10 new y axes.
This is creating TWO additional y axes for one of your subplots.
fig, axs = plt.subplots(2,1)axs[0] are the axes for the first subplot. axs[1] are the axes for the second subplot.
This is creating ONE additional y axis for each of your subplots.
twin0 = axs[0].twinx() # Calling twinx() once for axs[0] creates 2nd y axis for first subplot twin1 = axs[1].twinx() # calling twinx() once for axs[1] creates 2nd y axis for second subplotEach of your subplots now has 2 y axes
What you did in your initial post was treat twinx() like it returned a 2nd y axis. It does not. twinx() creates a new y axis. If you call twinx() ten times it will create 10 new y axes.
This is creating TWO additional y axes for one of your subplots.
axs[0].twinx().set_ylabel('SPX Price') # This creates a new axis (#2 y axis for the first subplot) axs[0].plot(sample_df['Spread_Price'],color='red') axs[0].twinx().plot(sample_df['SPX']) # This also creates a new y axis (#3 y axis for the first subplot)For proof you could rewrite your original code like this.
import matplotlib.pyplot as plt import pandas as pd sample_data = [[3000,18], [3200,17], [3500,16], [4000,12]] sample_df = pd.DataFrame(sample_data, columns = ['SPX', 'Spread_Price']) fig, axs = plt.subplots(2,1) axs[0].set_ylabel('Spread Price') a = axs[0].twinx() a.set_ylabel('SPX Price') b = axs[0].twinx() b.twinx().plot(sample_df['SPX']) axs[1].twinx().plot(sample_df['Spread_Price']) axs[1].plot(sample_df['SPX'],color='red') c = axs[0].twinx() c.twinx().set_yticklabels([]) print("These are all different axes", id(a), id(b), id(c)) plt.tight_layout() plt.show()