python - 在 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。谢谢!
解决方案
为自己吸取的教训——阅读文档!
正如上面的评论所说,解决方案应该像使用一样简单:
fig, ax = plt.subplots(nrows=5, ncols=2, sharex='col', sharey='col')
推荐阅读
- swift - 如何检测安装或升级的 iOS 应用程序,因为 iCloud 备份使 UserDefaults 解决方案无效
- woocommerce - 如何在愿望清单页面的产品缩略图上显示销售百分比徽章
- html - XSLT:根据当前上下文读取其他节点的值(非属性)
- tensorflow - 如何将 TF 冻结图 .pb 文件转换为 Keras .h5 (hdf5) 格式?(注意这是冻结图 pb 而不是 TF 保存的模型 PB)
- node.js - 在 Node.js 中获取默认用户数据目录
- javascript - jquery 移动加载器在 Firefox 上不起作用
- reactjs - react js仅在第一页显示一些内容,但所有内容都显示在页面url上,如seemore
- node.js - Feathers js - 如何通过谷歌登录
- pandas - pyspark 转换 DataFrame cols 的子集,但保留索引
- python - UART指纹如何将python3中的特征值上传到设备