Search code examples
pythonnumpymatplotlibpdfsavefig

How to save a matplotlib figure with automatic height to pdf


I have the following problem: I want to save a figure with a specific width, but auto-determine its height. Let's look at an example:

import matplotlib.pyplot as plt
import numpy as np

fig,ax=plt.subplots(figsize=(5,5),layout='constrained')
x=np.linspace(0,2*np.pi)
y=np.sin(x)
ax.set_aspect('equal')
ax.plot(x,y)
plt.show()
fig.savefig('test.pdf',format='pdf')

Here, I want the figure to be 5 inches wide, I want the axis to use up all the horizontal space, but I don't really care about the exact vertical size. Basically exactly, what plt.show() gives me:

plt.show() output

fig.savefig() gives me a lot of whitespace on top and below the figure (obviously, because I have defined figsize=(5,5)). Using the option bbox_inches='tight' almost does what I want to, but it re-sizes the x-direction of the figure (in this case to roughly 5.1 inches).

I have thus not found any way of saving this figure with a width of exactly 5 inches but an auto-determined height. The only way I can achieve what I want is to manually decrease the figsize until I see that the figure starts shrinking in x-direction.


Solution

  • Thanks to RuthC for providing the answer in a comment, the following seems to solve my problem:

    fig.savefig('test.pdf', format='pdf',bbox_inches='tight', pad_inches='layout')
    

    https://matplotlib.org/stable/users/prev_whats_new/whats_new_3.8.0.html#pad-inches-layout-for-savefig