0

I have a matplotlib gridspec plot as below:

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

enter image description here

I want to add gridlines for the above plot. I'm not able to do that with hlines as gridpec attribute has no object hlines.

Is it possible to add gridlines for gridspec object in matplotlib as below:

enter image description here

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Ailurophile
  • 2,552
  • 7
  • 21
  • 46
  • https://discourse.matplotlib.org/t/horizontal-and-vertical-lines-between-subplots/13540 this might be helpful – S P Sharan Jan 04 '22 at 15:21

1 Answers1

0

This is a bit complicated, but the following solution takes into account decorations on the axes (note how the grid goes below the xlabel). You could probably simplify if you know exactly where your axes are going to be:

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

enter image description here

Jody Klymak
  • 4,979
  • 2
  • 15
  • 31