Home > Blockchain >  Matplotlib lock ylim so it can't be adjusted while panning in UI
Matplotlib lock ylim so it can't be adjusted while panning in UI

Time:09-14

I have subplots that are locked in X, and I like to 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?

CodePudding user response:

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);
  • Related