首页 > 解决方案 > 在 matplotlib 中,同步子图的轴限制的最佳方法是什么(类似于 matlab `linkaxes()`)?

问题描述

我有一个两列图,其中左侧和右侧列具有不同的比例,因此我不能使用fig, ax = plt.subplots(nrows=5, ncols=2, sharex=True, sharey=True) 的全局语句。我的目标是同步子图每列的 x 和 y 限制,这样当我在 jupyter 中与widget后端一起放大和缩小时,每列都会自行同步。

这是我在堆栈溢出中发现的一种基于解决方案的想法:

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()

这将生成一个两列图像,允许理想的 x 和 y 限制同步。但我想知道是否有更简洁的方法来做到这一点——类似于 matlab 的linkaxes()function。谢谢!

在此处输入图像描述

标签: pythonmatplotlib

解决方案


为自己吸取的教训——阅读文档!
正如上面的评论所说,解决方案应该像使用一样简单:
fig, ax = plt.subplots(nrows=5, ncols=2, sharex='col', sharey='col')


推荐阅读