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?
1
You can use the matplotlib.backends.backend_pdf.PdfPages
module. Here’s the code for it:
import matplotlib.pyplot as plt
from matplotlib.backends.backend_pdf import PdfPages
x = [1, 2, 3, 4]
y = [3, 5, 4, 7]
# Creating the figure
fig, ax = plt.subplots()
ax.scatter(x, y)
page_width, page_height = 8.3, 11.7 # A4 size in inches
with PdfPages("example_with_whitespace.pdf") as pdf:
fig.set_size_inches(page_width, page_height)
#Center the figure by using `tight_layout`
pdf.savefig(fig, bbox_inches="tight", dpi=300, pad_inches=2.0)
Use fig.set_size_inches(width, height)
to control the size of the figure. And pad_inches
helps to add whitespace around the figure.
This approach will ensure your figure is centered with whitespace around it on a standard-sized PDF page.
Pratyush Goutam is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.