matplotlib中子批次之间的垂直分隔符

2024-10-01 09:38:00 发布

您现在位置:Python中文网/ 问答频道 /正文

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

enter image description here

我想在第四列和第五列之间添加一条垂直分隔线。我对this answer进行了如下修改,在我的主代码之后添加了以下内容:

# 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)

然而,结果是:

enter image description here

线路显然不太正确。我已经尝试过改变我从(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)

Tags: theinfalseforgetrateparamsax
1条回答
网友
1楼 · 发布于 2024-10-01 09:38:00

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

下面的方法适用于精细的w/constrained_布局,并允许您调整图形的大小。它制作了一个虚拟轴以使线条进入,并使用宽度_比使虚拟轴非常小:

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()

enter image description here

相关问题 更多 >