trouble aligning ticks for matplotlib twinx axes

Viewed 8758

I 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 pulling the data from excel files, so there is no way to know the max limits beforehand. I have tried the following code.

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

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

The problem now is that the ticks on ax2 do not have labels anymore. Can anyone give me a good way to align ticks with different scales?

2 Answers

To anyone who's wondering (and for my future reference), the lambda function f in ImportanceofBeingErnest's answer maps the input left tick to a corresponding right tick through:

RHS tick = Bottom RHS tick + (% of LHS range traversed * RHS range)

Refer to this question on tick formatting to truncate decimal places:

from matplotlib.ticker import FormatStrFormatter

ax2.yaxis.set_major_formatter(FormatStrFormatter('%.2f')) # ax2 is the RHS y-axis
Related