我有一个两列图,其中左侧和右侧列具有不同的比例,因此我无法使用 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 。谢谢!
最佳答案
我自己学到的经验教训——阅读文档!
正如上面的评论所说,解决方案应该像使用一样简单:
fig, ax = plt.subplots(nrows=5, ncols=2, sharex='col', sharey='col')
关于python - 在 matplotlib 中,同步子图轴限制的最佳方法是什么(类似于 matlab `linkaxes()` )?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52713217/