繁体   English   中英

matplotlib 中子图之间的垂直分隔符

[英]Vertical separator between subplots in matplotlib

我用matplotlib创建了这个图(下面的完整代码):

在此处输入图像描述

我想在第四列和第五列之间添加一条垂直分隔线。 我按如下方式调整了这个答案,在我的主要代码之后添加了这个:

# Get the bounding boxes of the axes including text decorations
r = fig0.canvas.get_renderer()
get_bbox = lambda ax: ax.get_tightbbox(r).transformed(fig0.transFigure.inverted())
xmin = get_bbox(ax10).x0 # ax10 is the 5th column, 2nd row with the left ticklabels
xmax = get_bbox(ax15).x1 # ax15 is the 4th column, 2nd row with the right ticklabels
xs = (xmax+xmin)/2
line = plt.Line2D([xs], [0,1], transform=fig0.transFigure, color='k')
fig0.add_artist(line)

然而,结果是这样的:

在此处输入图像描述

这条线显然不在正确的位置。 我尝试更改从(上面代码中的ax10ax15 )获取 x 坐标的轴,但这无济于事。 我究竟做错了什么?

我怀疑这是因为我在图中使用了constrained_layout=True 如果可能的话,我想继续这样做,因为它可以完美地对轴进行分组,而不需要gridspec

该图的完整代码:

fig0, ((ax0, ax1, ax2, ax3, ax4, ax5), (ax6, ax7, ax8, ax9, ax10, ax11)) = plt.subplots(
    2, 6, figsize=[18, 5], sharex=True, constrained_layout=True)

row0 = [ax0, ax1, ax2, ax3, ax4, ax5]
row1a = [ax6, ax7, ax8, ax9, ax10, ax11]

ax12, ax13, ax14, ax15, ax16, ax17 = [ax.twinx() for ax in row1a]
row1b = [ax12, ax13, ax14, ax15, ax16, ax17]

ax_list = [axs for axs in zip(row0, row1a, row1b)]

for row in [row0, row1a, row1b]:
    for ax in row[1:4]:
        ax.sharey(row[0])
    row[4].sharey(row[5])

for row in [row0, row1a]:
    for ax in row[1:4]:
        ax.tick_params(labelleft=False)

ax4.yaxis.tick_right()
ax5.yaxis.tick_right()
ax4.tick_params(labelright=False)

ax11.tick_params(labelleft=False)
ax16.tick_params(labelright=False)

for ax in row1a[1:4]:
    ax.tick_params(labelleft=False)
    
for ax in row1b[0:3]:
    ax.tick_params(labelright=False)

for rate, axs in zip(rateslist, ax_list):
    axa, axb, axc = axs
    
    axa.plot(t.loc[rate[0]])
    axb.plot(t.loc[rate[1]]/t.loc[rate[1], '1999'], color='g')
    axc.plot(t.loc[rate[2]]/t.loc[rate[2], '1999'], color='r')
    
    loc = mticker.MultipleLocator(base=8)
    axb.xaxis.set_major_locator(loc)
    axb.tick_params(axis='x', labelsize=6, labelrotation=90)

如果您在获取边界框之前进行绘制,您上面的代码可能会正常工作。

下面的方法在使用 constrained_layout 时效果很好,它允许您调整图形的大小。 它为 go 的线制作了一个假轴,并使用 width_ratio 使该假轴变得非常小:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms

fig = plt.figure(constrained_layout=True)
gs = fig.add_gridspec(2, 7, width_ratios=[1, 1, 1, 1, 0.01, 1, 1])

axs = np.zeros((2, 6), dtype='object')
for ind in range(6):
    i = ind
    if ind>=4:
        i = ind+1
    axs[0, int(ind)] = fig.add_subplot(gs[0, i])
    axs[1, ind] = fig.add_subplot(gs[1, i])

axline = fig.add_subplot(gs[:, 4])
axline.axis('off')
trans = mtransforms.blended_transform_factory(
    axline.transAxes, fig.transFigure)
axline.plot([0,0], [0, 1], 'r', transform=trans, clip_on=False)

plt.show()

在此处输入图像描述

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM