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

我有一个图,该图包含三个子图,排列在同一列中。这些地块之一在右侧使用了3个y轴刺。我按照本教程在子图上插入多个右轴脊椎。

我的问题是,通过添加额外的刺,图中的所有子图在 x 方向上都变小了。这更改了所有三个子图的宽度,从而在其他子图的右侧保留了未使用的空间。

在y轴上添加额外的棘刺时,如何仅调整一个子图的宽度?

下面是一个简化的示例,它产生了此图中所示的相同问题

http://img1.mukewang.com/60b5e82c0001d9fa16110942.jpg

from matplotlib import pyplot as plt


# set up a set of three subplots

fig = 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 tutorial

def 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 plots

plt.tight_layout()

plt.show()

http://img.mukewang.com/60b5e84000010af416820942.jpg

matplotlib版本2.1.2


绝地无双
浏览 214回答 3
3回答

慕的地6264312

解决问题的另一种解决方法gridspec,您还必须在其中手动设置中间图的右侧极限。但是您会像原始代码中那样,坚持使用3行1列的格式。只需用以下几行替换函数定义之前的代码:import matplotlib.gridspec as gridspecgs = 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 boundax_2_l = plt.subplot(gs[1])ax_2_r = ax_2_l.twinx()输出

HUX布斯

一个可能的答案是使用 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 略小,以便为刺留出空间。(还是反复试验的方法,所以不是完美的解决方案)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python