Malfunctioning tick alignment for matplotlib twinx axes

I have created a matplotlib plot that has 2 y-axes. The y-axes have different scales, but I want the ticks and grid to be aligned. I am fetching data from excel files so I cannot know the maximum limits beforehand. I have tried the following code.

# creates double-y axis
ax2 = ax1.twinx()

locs = ax1.yaxis.get_ticklocs()
ax2.set_yticks(locs) 

      

Now the problem is that the ticks on ax2 no longer have labels. Can anyone give me a good way to align ticks with different scales?

+3


source to share


1 answer


Aligning the tick positions of two different scales would mean abandoning the pretty automatic tick pointer and setting ticks to the same positions on the secondary axes as on the original.

The idea is to establish a relationship between the scales of two axes using a function and set the ticks of the second axes to the positions of those that the first have.

enter image description here



import matplotlib.pyplot as plt
import matplotlib.ticker

fig, ax = plt.subplots()
# creates double-y axis
ax2 = ax.twinx()

ax.plot(range(5), [1,2,3,4,5])
ax2.plot(range(6), [13,17,14,13,16,12])
ax.grid()

l = ax.get_ylim()
l2 = ax2.get_ylim()
f = lambda x : l2[0]+(x-l[0])/(l[1]-l[0])*(l2[1]-l2[0])
ticks = f(ax.get_yticks())
ax2.yaxis.set_major_locator(matplotlib.ticker.FixedLocator(ticks))

plt.show()

      

Please note that this is a general case solution and it can cause completely unreadable labels to be based on use case. Better solutions are possible if you have more a priori information about the axis range.

Also see this question for the case where the automatic placement of the first axis labels is sacrificed to more easily set the tick placement of the secondary axis.

+3


source







All Articles