为了账号安全,请及时绑定邮箱和手机立即绑定

使用 matplotlib 显示多个 y 轴脊时减少一个子图的宽度

使用 matplotlib 显示多个 y 轴脊时减少一个子图的宽度

绝地无双 2021-05-30 03:04:29
我有一个图,该图包含三个子图,排列在同一列中。这些地块之一在右侧使用了3个y轴刺。我按照本教程在子图上插入多个右轴脊椎。我的问题是,通过添加额外的刺,图中的所有子图在 x 方向上都变小了。这更改了所有三个子图的宽度,从而在其他子图的右侧保留了未使用的空间。在y轴上添加额外的棘刺时,如何仅调整一个子图的宽度?下面是一个简化的示例,它产生了此图中所示的相同问题from matplotlib import pyplot as plt# set up a set of three subplotsfig = plt.figure(figsize=(17, 11))ax_1_l = fig.add_subplot(3,1,1)ax_1_r = ax_1_l.twinx()ax_2_l = fig.add_subplot(3,1,2)ax_2_r = ax_2_l.twinx()ax_3_l = fig.add_subplot(3,1,3)ax_3_r = ax_3_l.twinx()# add additional axes to the middle subplot as per tutorialdef make_patch_and_spines_invisible(ax):  ax.set_frame_on(True)  ax.patch.set_visible(False)  for sp in ax.spines.values():    sp.set_visible(False)ax_2_r_2 = ax_2_l.twinx()make_patch_and_spines_invisible(ax_2_r_2)ax_2_r_2.spines['right'].set_position(('axes', 1.05))ax_2_r_2.spines['right'].set_visible(True)ax_2_r_3 = ax_2_l.twinx()make_patch_and_spines_invisible(ax_2_r_3)ax_2_r_3.spines['right'].set_position(('axes', 1.1))ax_2_r_3.spines['right'].set_visible(True)# display the plotsplt.tight_layout()plt.show()matplotlib版本2.1.2
查看完整描述

3 回答

?
慕的地6264312

TA贡献1817条经验 获得超6个赞

解决问题的另一种解决方法gridspec,您还必须在其中手动设置中间图的右侧极限。但是您会像原始代码中那样,坚持使用3行1列的格式。只需用以下几行替换函数定义之前的代码:


import matplotlib.gridspec as gridspec

gs = gridspec.GridSpec(3, 1)


ax_1_l = plt.subplot(gs[0])

ax_3_l = plt.subplot(gs[2])

ax_1_r = ax_1_l.twinx()

ax_3_r = ax_3_l.twinx()


gs = gridspec.GridSpec(3, 1)

gs.update(right=0.85)  # This is the part where you specify the bound

ax_2_l = plt.subplot(gs[1])

ax_2_r = ax_2_l.twinx()

输出

//img1.sycdn.imooc.com//60b5e8500001a59905330283.jpg

查看完整回答
反对 回复 2021-06-01
?
HUX布斯

TA贡献1876条经验 获得超6个赞

一个可能的答案是使用 matplotlibssubplot2grid功能。缺点是它不会自动调整尺寸,你必须手动调整。


将子图的创建替换为:


ax_1_l = plt.subplot2grid((3, 11), (0, 0), colspan=11)

ax_2_l = plt.subplot2grid((3, 11), (1, 0), colspan=10)

ax_3_l = plt.subplot2grid((3, 11), (2, 0), colspan=11)


ax_1_r = ax_1_l.twinx()

ax_2_r = ax_2_l.twinx()

ax_3_r = ax_3_l.twinx()

我制作了一个 3 行 11 列的网格,然后设置colspan子图 2 使子图 2 比其他 2 略小,以便为刺留出空间。(还是反复试验的方法,所以不是完美的解决方案)

//img1.sycdn.imooc.com//60b5e8680001660a12290708.jpg

查看完整回答
反对 回复 2021-06-01
  • 3 回答
  • 0 关注
  • 213 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号