Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

How to remove padding around plot in Matplotlib

📅 2015-Jul-29 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ matplotlib, padding, plot ⬩ 📚 Archive

The plot generated by Matplotlib typically has a lot of padding around it. This is useful if you are viewing or displaying the plot in isolation. However, when the plot is embedded inside another document, typically extra padding is added around and makes the plot look tiny. The solution is to reduce or remove the padding around the plot generated by Matplotlib.

This can be done by configuring the bounding box used for the plot while saving it to disk:

import matplotlib.pyplot as mplot
mplot.savefig("foo.pdf", bbox_inches="tight")

This makes the bounding box tight around the plot, while still giving enough space for the text or lines on the plot periphery.

If you want a plot with zero padding around it:

import matplotlib.pyplot as mplot
mplot.savefig("foo.pdf", bbox_inches="tight", pad_inches=0)

Personally, I find this too tight, but it might be useful in some situations.

Tried with: Matplotlib 1.4.3, Python 2.7.3 and Ubuntu 14.04

© 2022 Ashwin Nanjappa • All writing under CC BY-SA license • 🐘📧