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

标签 python matplotlib

我有一个两列图,其中左侧和右侧列具有不同的比例,因此我无法使用 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 的 linkaxes() function 。谢谢!

enter image description here

最佳答案

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

关于python - 在 matplotlib 中,同步子图轴限制的最佳方法是什么(类似于 matlab `linkaxes()` )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52713217/

相关文章:

python - yield 中的合并排序函数出错

python - matplotlib,Python : part of title in bold font

python - 如何在 matplotlib python 中动态更改 alpha 值

Python:如何根据元组中指定的多个条件从 csv 文件中提取行

python - 有效过滤掉两个二维 numpy 数组之间的匹配行

python - 当外部模块已经导入到其他导入模块中时,是否必须重新导入外部模块?

python - 安装了 matplotlib 3 次仍然出现错误 : ImportError: No module named backends. backend_wxagg

python - 将缺失日期转发到 Python Pandas Dataframe

python - 了解 matplotlib 中 subplot 和 add_subplot(散点)图之间的区别

python - 如何在 Ipython 中显示与内联的 matplotlib 图交错的打印语句?