I have generated a matplotlib
figure that I want to save to a PDF. So far, this is straightforward.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [3, 5, 4, 7]
plt.scatter(x, y)
plt.savefig(
"example.pdf",
bbox_inches = "tight"
)
plt.close()
However, I would like the figure to appear in the middle of a standard page and have some white space around the figure, rather than fill up the entire page. How can I tweak the above to achieve this?
Another option is to use constrained layout and set a rectangle that you want the all the plot elements to be contained in.
import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [3, 5, 4, 7]
fig, ax = plt.subplots(figsize=(8.3, 11.7), layout='constrained')
fig.get_layout_engine().set(rect=(0.15, 0.3, 0.7, 0.4)) # left, bottom, width, height in fractions of the figure
ax.scatter(x, y)
fig.savefig('example.pdf')
plt.close()