In the example below, I create a plot in Matplotlib with a constrained layout, in which the thickness of the left and bottom axes spines are greatly increased (and the top and right ones are turned off), and the ticks and tick labels are removed. When I display or save the figure, the spines are slightly cropped. Does anyone know how to fix this while maintaining the use of the constrained layout?
from matplotlib import pyplot as plt
fig, ax = plt.subplots(layout="constrained")
x = [[1, 2], [3, 4]]
ax.imshow(x)
ax.spines[["right", "top"]].set_visible(False)
ax.spines[["left", "bottom"]].set_linewidth(14)
ax.spines[["left", "bottom"]].set_capstyle("round")
ax.tick_params(
axis="both", bottom=False, left=False, labelbottom=False, labelleft=False
)
fig.savefig("example.png", dpi=150)
As stated in the constrained layout guide,
- Constrained layout only considers ticklabels, axis labels, titles, and legends. Thus, other artists may be clipped and also may overlap.
So, in particular given that the ticks and tick labels are removed, the axes spine thickness is not considered in the calculation for determining the constraints.
However, within a constrained layout, you can still manually set certain things, for example, the minimum padding around the axes. So, an updated example without the clipping would be:
from matplotlib import pyplot as plt
fig, ax = plt.subplots(layout="constrained")
x = [[1, 2], [3, 4]]
ax.imshow(x)
ax.spines[["right", "top"]].set_visible(False)
ax.spines[["left", "bottom"]].set_linewidth(14)
ax.spines[["left", "bottom"]].set_capstyle("round")
ax.tick_params(
axis="both", bottom=False, left=False, labelbottom=False, labelleft=False
)
# set the _minimum_ padding around the axes (values are in inches)
fig.get_layout_engine().set(w_pad=0.15, h_pad=0.15)
fig.savefig("example.png", dpi=150)