6
votes

I'd like to add a second y-axis to my plot plt.plot([1,2,4]) on the right side, which should be aligned with the left axis, but in different units which can be calculated.

For example a scaling to 1. So effectively the left y-axis will be [1,2,3,4] and the right should be [0.25, 0.5, 0.75, 1.0] and properly aligned.

How can I do that in matplotlib?

(the twin axis example seems to handle a different use-case where you have un-aligned axes on different data)

1
a quick workaround would be to use twiny and manually provide limits for that axis that are based on the limits of the left-hand side y-axis ... but I'm aware that this is not the solution you are looking for... - mommermi
Adapt the gallery's celsius-or-fahrenheit example: matplotlib.org/examples/subplots_axes_and_figures/… - cphlewis
@cphlewis: Thanks. That works. I just had to be careful not to use plt. thereafter, or it gets confused. - Gerenuk
Yes, this crosses the boundary from the pyplot/matlab style to where OO style works better -- nice summary - cphlewis
Does this answer your question? How to add a second x-axis in matplotlib - G M

1 Answers

3
votes

This was answered in a link in the comments, but I'd like to add the solution here in case that link breaks. Basically you make a twin axis, and use callbacks.connect to make sure the new axis updates whenever the original does. As such, the connection code needs to go before the plotting commands. Using the OP's example:

import matplotlib.pyplot as plt

x = [1,2,3,4]

fig, ax1 = plt.subplots()

# add second axis with different units, update it whenever ax1 changes
ax2 = ax1.twinx()

def convert_ax2(ax1):
    y1, y2 = ax1.get_ylim()
    ax2.set_ylim(y1/max(x), y2/max(x))
    ax2.figure.canvas.draw()    

ax1.callbacks.connect("ylim_changed", convert_ax2)   

ax1.plot(x)

plot with two axes