1

I have subplots whose ylims I want to keep locked, so I can scroll through them using matplotlib's UI. I just want to pan through in the x direction, but sometimes I accidentally pan up/down so that the data pans off screen. Here is an example of an oops:

panning disaster

What can I do so this doesn't happen? I set the ylims programmatically, and that sets them up fine initially , but doesn't stop me from panning accidentally:

xvals = np.arange(0,1000,0.1)
yvals1 = np.sin(3*xvals)
yvals2 = yvals1 + 30

f, (ax1, ax2) = plt.subplots(2,1,sharex = True);
ax1.plot(xvals, yvals1)
ax1.set_xlim(2,5)
ax1.set_ylim(-1.3,1.3)
ax2.plot(xvals, yvals2);

Is there a way to lock those ylims in place so I can't pan the data off the axes?

eric
  • 7,142
  • 12
  • 72
  • 138

1 Answers1

2

Basically you could hold the x key during the pan.

A solution doing that automatically for your plot based on a combination of two other answers:
simonb answer on atplotlib forcing pan/zoom to constrain to x-axes
ajdawson answer on How do I change matplotlib's subplot projection of an existing axis?

import matplotlib
import matplotlib.pyplot as plt


class My_Axes(matplotlib.axes.Axes):
    name = "My_Axes"
    def drag_pan(self, button, key, x, y):
        matplotlib.axes.Axes.drag_pan(self, button, 'x', x, y) # pretend key=='x'

matplotlib.projections.register_projection(My_Axes)


xvals = np.arange(0,1000,0.1)
yvals1 = np.sin(3*xvals)
yvals2 = yvals1 + 30

f, (ax1, ax2) = plt.subplots(2,1,sharex = True, subplot_kw={'projection': "My_Axes"});
ax1.plot(xvals, yvals1)
ax1.set_xlim(2,5)
ax1.set_ylim(-1.3,1.3)
ax2.plot(xvals, yvals2);
MagnusO_O
  • 1,202
  • 4
  • 13
  • 19
  • 1
    Ha I didn't know the keyboard 'x' trick that is really helpful, and this is a nice way to implement it programmatically. – eric Sep 13 '22 at 18:51
  • 1
    @eric got that hold key from [matplotlib interactive navigation](https://matplotlib.org/3.2.2/users/navigation_toolbar.html) - that links to an old version, but that docu page is imho better illustrated than the current one – MagnusO_O Sep 13 '22 at 18:56