matplotlib 如何在每个GridSpec子图之间添加网格线

0dxa2lsx  于 2023-04-07  发布在  其他
关注(0)|答案(1)|浏览(193)

我有一个matplotlibgridspec图如下:

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig2 = plt.figure(figsize=[8,8])
spec2 = gridspec.GridSpec(ncols=2, nrows=2, figure=fig2)
f2_ax1 = fig2.add_subplot(spec2[0, 0])
f2_ax2 = fig2.add_subplot(spec2[0, 1])
f2_ax3 = fig2.add_subplot(spec2[1, 0])
f2_ax4 = fig2.add_subplot(spec2[1, 1])

我想为上面的图添加网格线。我不能用hlines这样做,因为gridpec属性没有对象hlines
是否可以在matplotlib中为gridspec对象添加网格线,如下所示:

llmtgqce

llmtgqce1#

这有点复杂,但以下解决方案考虑了轴上的装饰(注意xlabel下方的网格)。如果您确切地知道轴的位置,您可能会简化:

import matplotlib.pyplot as plt
import numpy as np
import matplotlib as mpl

fig, axs = plt.subplots(2, 2, constrained_layout=True)

axs[0, 0].set_xlabel('Boo')
fig.draw_without_rendering()

trans = fig.transFigure

# line after the first column:
right = 0
for a in axs[:, 0]:
    bb = trans.inverted().transform_bbox(a.get_tightbbox(renderer=fig.canvas.get_renderer()))
    right = max(right, bb.x1)
right = right + 0.01
fig.add_artist(mpl.lines.Line2D([right, right], [0, 1], linestyle='--'))

# line after first row
bottom = 1
for a in axs[0, :]:
    bb = trans.inverted().transform_bbox(a.get_tightbbox(renderer=fig.canvas.get_renderer()))
    bottom = min(bottom, bb.y0)
bottom = bottom - 0.01
fig.add_artist(mpl.lines.Line2D([0, 1], [bottom, bottom], linestyle='--'), )
plt.show()

相关问题