You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

能否在plt.subplot_mosaic()中使用sharey='row'参数?

在plt.subplot_mosaic()中实现整行共享Y轴的正确方法

不能直接把sharey='row'塞进fig_kw参数里——你报错的原因就是fig_kw是传给plt.figure()的配置项,而sharey='row'是控制子图布局共享轴的参数,不属于figure的参数范畴,自然会提示类型错误。

正确的做法是把sharey='row'直接作为plt.subplot_mosaic()的参数传入,而非嵌套在fig_kw里。举个实际例子:

import matplotlib.pyplot as plt

# 定义马赛克布局结构
mosaic_layout = [
    ['upper_left', 'upper_right'],
    ['lower_left', 'lower_right']
]

# 直接传入sharey='row'参数
fig, ax_map = plt.subplot_mosaic(mosaic_layout, sharey='row')

# 测试数据验证效果
ax_map['upper_left'].plot([1,2,3], [2,4,6])
ax_map['upper_right'].plot([1,2,3], [3,6,9])
ax_map['lower_left'].plot([1,2,3], [5,10,15])
ax_map['lower_right'].plot([1,2,3], [7,14,21])

plt.show()

运行后每行的子图会自动共享Y轴,不用再逐个调用Axes.sharey()手动配置。

注意:这个用法要求matplotlib版本在3.6及以上,如果版本过旧,subplot_mosaic可能不支持sharey='row'这种字符串取值,建议升级到新版简化操作。

内容的提问来源于stack exchange,提问作者mins

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 10:12:06