Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

One way to zoom multiple subplots together using Matplotlib/Pyplot is to use the ylim() and xlim() methods of the Axes object.

Here's an example:

import matplotlib.pyplot as plt

fig, axs = plt.subplots(2, 2)

# plot some data on each subplot
axs[0,0].plot([1,2,3], [1,2,3])
axs[0,1].plot([1,2,3], [1,2,3])
axs[1,0].plot([1,2,3], [1,2,3])
axs[1,1].plot([1,2,3], [1,2,3])

# set the initial x and y limits for all subplots
xmin, xmax = 0, 4
ymin, ymax = 0, 4
for ax in axs.flatten():
    ax.set_xlim(xmin, xmax)
    ax.set_ylim(ymin, ymax)

# define the event handler for zooming
def on_xlim_changed(ax):
    xlim = ax.get_xlim()
    ylim = ax.get_ylim()
    for axx in axs.flatten():
        axx.set_xlim(xlim)
        axx.set_ylim(ylim)

# connect the event handler to each subplot
for ax in axs.flatten():
    ax.callbacks.connect('xlim_changed', on_xlim_changed)

plt.show()

In this example, we have created a 2x2 grid of subplots and plotted some data on each one. We have also set the initial x and y limits for all subplots to be the same.

Then, we define an event handler function on_xlim_changed() that will be called whenever the x limits of any subplot are changed. This function simply gets the new x and y limits from the changed subplot, and then sets the same limits on all subplots.

Finally, we connect the on_xlim_changed() function to each subplot using the callbacks.connect() method.

Now, when we zoom in or out on one of the subplots, all of the subplots will be zoomed together, since they all have the same x and y limits.