I want to add a coloured border to some subplots with a fixed width specified in pixels. I wrote the following function to do so by adding a Rectangle
patch to the figure behind the axes.
def add_subplot_border(ax, width=0, color=None):
fig = ax.get_figure()
# Convert bottom-left and top-right to display coordinates
x0, y0 = ax.transAxes.transform((0, 0))
x1, y1 = ax.transAxes.transform((1, 1))
# Adjust margins
x0 -= width
x1 += width
y0 -= width
y1 += width
# Convert back to Axes coordinates
x0, y0 = ax.transAxes.inverted().transform((x0, y0))
x1, y1 = ax.transAxes.inverted().transform((x1, y1))
rect = plt.Rectangle((x0, y0), x1-x0, y1-y0,
color=color,
transform=ax.transAxes,
zorder=-1)
fig.patches.append(rect)
This appears to be a good starting point, but when the figure is resized the relative thickness of the border changes too. How can I specify a transform to scale and translate the patch to appear as a fixed-width border regardless of window scaling? Or, is there a better way to approach this?
Original figure
Scaled figure - uneven border