我用matplotlib
创建了这个图(下面是完整的代码):
我想在第四列和第五列之间添加一条垂直分隔线。我对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)
然而,结果是:
线路显然不太正确。我已经尝试过改变我从(ax10
和ax15
中获取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)
如果在获取边界框之前进行绘制,则上面的代码可能工作正常
下面的方法适用于精细的w/constrained_布局,并允许您调整图形的大小。它制作了一个虚拟轴以使线条进入,并使用宽度_比使虚拟轴非常小:
相关问题 更多 >
编程相关推荐