Matplotlib/Pyplot: How to zoom subplots together?
Asked Answered
A

4

99

I have plots of 3-axis accelerometer time-series data (t,x,y,z) in separate subplots I'd like to zoom together. That is, when I use the "Zoom to Rectangle" tool on one plot, when I release the mouse all 3 plots zoom together.

Previously, I simply plotted all 3 axes on a single plot using different colors. But this is useful only with small amounts of data: I have over 2 million data points, so the last axis plotted obscures the other two. Hence the need for separate subplots.

I know I can capture matplotlib/pyplot mouse events (http://matplotlib.sourceforge.net/users/event_handling.html), and I know I can catch other events (http://matplotlib.sourceforge.net/api/backend_bases_api.html#matplotlib.backend_bases.ResizeEvent), but I don't know how to tell what zoom has been requested on any one subplot, and how to replicate it on the other two subplots.

I suspect I have the all the pieces, and need only that one last precious clue...

-BobC

Aught answered 17/11, 2010 at 0:58 Comment(2)
IMO the best documentation is the example code they provide: matplotlib.org/examples/pylab_examples/shared_axis_demo.htmlPlasmo
True! I wish that page existed when I asked my question. So good it's there now.Aught
L
154

The easiest way to do this is by using the sharex and/or sharey keywords when creating the axes:

from matplotlib import pyplot as plt

ax1 = plt.subplot(2,1,1)
ax1.plot(...)
ax2 = plt.subplot(2,1,2, sharex=ax1)
ax2.plot(...)
Leftwich answered 17/11, 2010 at 1:38 Comment(0)
E
75

You can also do this with plt.subplots, if that's your style.

fig, ax = plt.subplots(3, 1, sharex=True, sharey=True)
Endogen answered 20/9, 2017 at 18:47 Comment(0)
A
-1

I call the following function after making plots to get them linked together. It will get all subplots from the current figure, and link their x axes.

import matplotlib.pyplot as plt
def linkx():
  # Get current figure
  axes = plt.gcf().axes 
  parent = axes[0]
  # Loop over other axes and link to first axes
  for i in range(1,len(axes)): 
    axes[i].sharex(parent)
Anacoluthia answered 18/3, 2023 at 17:6 Comment(0)
W
-2

Interactively this works on separate axes

for ax in fig.axes:
    ax.set_xlim(0, 50)
fig.draw()
Wattenberg answered 6/1, 2015 at 13:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.