3

I have a two-column figure, where the left-hand-side and the right-hand-side column have different scales so I can't use a global statement of fig, ax = plt.subplots(nrows=5, ncols=2, sharex=True, sharey=True). My goal is to synchronize x and y limits for each column of the subplots, so that when I zoom in and out in jupyter with widget backend, each column is synchronized on their own.

Here are one solution based ideas I found on stack overflow:

import numpy as np
import matplotlib.pyplot as plt

# Make fake data
# fake data for left-hand-side subplots column
x1 = np.linspace(0, 4 * np.pi, 50)
y1 = np.tile(np.sin(x1), (5, 1))

# fake data for left-hand-side subplots column
x2 = 2 * x1
y2 = 2 * abs(y1)

# Plotting
fig, ax = plt.subplots(nrows=5, ncols=2)
fig.subplots_adjust(wspace=0.5, hspace=0.1)
ax_ref1, ax_ref2 = (ax[0, 0], ax[0, 1])
for axi, y1_i in zip(ax[:, 0].flatten(), y1):
    axi.plot(x1, y1_i)
    # Link xlim and ylim of left-hand-side subplots
    ax_ref1.get_shared_x_axes().join(ax_ref1, axi)
    ax_ref1.get_shared_y_axes().join(ax_ref1, axi)
ax_ref1.set(title='Left-hand-side column')

for axi, y2_i in zip(ax[:, 1].flatten(), y2):
    axi.plot(x2, y2_i)
    # Link xlim and ylim of Right-hand-side subplots
    ax_ref2.get_shared_x_axes().join(ax_ref2, axi)
    ax_ref2.get_shared_y_axes().join(ax_ref2, axi)
ax_ref2.set(title='Right-hand-side column')
plt.show()

This will generate a two-column image that allows the desirable x and y limit synchronization. But I wonder if there is a more concise way to do this--something similar as matlab's linkaxes() function. Thanks!

enter image description here

Shan Dou
  • 3,088
  • 1
  • 20
  • 18
  • Possible duplicate of [matplotlib set shared axis](https://stackoverflow.com/questions/17329292/matplotlib-set-shared-axis) – Thomas Kühn Oct 09 '18 at 06:01
  • 1
    If the question I linked does not solve your problem, you can also do `sharex='col'` to only synchronise columns. I think there might be a question about that somewhere too. – Thomas Kühn Oct 09 '18 at 06:03
  • 1
    Right, see https://matplotlib.org/api/_as_gen/matplotlib.pyplot.subplots.html for a complete description of the options for `sharex` / `sharey` – SpghttCd Oct 09 '18 at 11:18
  • Oh wow, should have read the docs... `sharex='col', sharey='col'` is THE SOLUTION for my question. Had always thought they only take booleans. Thank you so much!! – Shan Dou Oct 09 '18 at 15:32

1 Answers1

1

Lessons learned for myself--Read the Docs!
As the comments above say, the solution should be as simple as using:
fig, ax = plt.subplots(nrows=5, ncols=2, sharex='col', sharey='col')

Shan Dou
  • 3,088
  • 1
  • 20
  • 18