在matplotlib中,同步子批次的轴限制的最佳方法是什么(类似于matlab的`linkaxes()`)?

2024-03-29 15:59:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个两列的图,左边和右边的列有不同的刻度,所以我不能使用fig, ax = plt.subplots(nrows=5, ncols=2, sharex=True, sharey=True的全局语句。我的目标是同步子批次中每一列的x和y限制,这样当我用widget后端在jupyter中放大和缩小时,每一列都是独立同步的。在

以下是我在堆栈溢出问题上发现的一个基于解决方案的想法:

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的^{} function。谢谢!在

enter image description here


Tags: forgetnpcolumnpltaxsidex1
1条回答
网友
1楼 · 发布于 2024-03-29 15:59:35

我从中学到的教训,请阅读文档!
正如上面的评论所说,解决方案应该简单到使用:
fig, ax = plt.subplots(nrows=5, ncols=2, sharex='col', sharey='col')

相关问题 更多 >