能否在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
相关产品推荐
相关产品推荐

