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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With