Programmatically control subplot adjustment
This example describes a user-defined way to read out Artist sizes and set the subplot parameters accordingly. Its main purpose is to illustrate some advanced concepts like reading out text positions, working with bounding boxes and transforms and using events. But it can also serve as a starting point if you want to automate the layouting and need more flexibility than tight layout and constrained layout.
Below, we collect the bounding boxes of all y-labels and move the left border of the subplot to the right so that it leaves enough room for the union of all the bounding boxes.
There's one catch with calculating text bounding boxes:
Querying the text bounding boxes (Text.get_window_extent) needs a
renderer (RendererBase instance), to calculate the text size. This renderer
is only available after the figure has been drawn (Figure.draw).
A solution to this is putting the adjustment logic in a draw callback. This function is executed after the figure has been drawn. It can now check if the subplot leaves enough room for the text. If not, the subplot parameters are updated and second draw is triggered.
import matplotlib.pyplot as plt
import matplotlib.transforms as mtransforms
fig, ax = plt.subplots()
ax.plot(range
Tags: component: subplot plot-type: line styling: position level: advanced