Python Forum
How to avoid the extra set of y-axis labels?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to avoid the extra set of y-axis labels?
#7
This creates two subplots. It returns a figure and an axes array.
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 subplot
Each 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()
Reply


Messages In This Thread
RE: How to avoid the extra set of y-axis labels? - by deanhystad - May-17-2022, 03:31 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  How can histogram bins be separated and reduce number of labels printed on x-axis? cadena 1 908 Sep-07-2022, 09:47 AM
Last Post: Larz60+
  Floor division problem with plotting x-axis tick labels Mark17 5 2,144 Apr-03-2022, 01:48 PM
Last Post: Mark17
  x-axis labels with Matplotlib Mark17 8 2,284 Mar-23-2022, 06:10 PM
Last Post: Mark17
  Sample labels from excel file in order to put them on x-axis and y-axis of a plot hobbyist 11 4,455 Sep-14-2021, 08:29 AM
Last Post: hobbyist
  How to preserve x-axis labels despite deleted subplot? Mark17 1 1,953 Dec-23-2020, 09:02 PM
Last Post: Mark17
  Difference Between Figure Axis and Sub Plot Axis in MatplotLib JoeDainton123 2 2,510 Aug-21-2020, 10:17 PM
Last Post: JoeDainton123
  An Extra 'None' leoahum 5 3,972 Oct-18-2018, 08:20 PM
Last Post: volcano63

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020