ecjb
ecjb

Reputation: 5459

Save an image in matplotlib which is both square (n_pixel x n_pixel) and without padding

I want to save an image as a square (having the same number of pixels in the 2 dimensions corresponding to n_pixel x n_pixel). I also want it to be saved without any padding on the side. For this, the following code saves the image (288x288 pixels), but there is padding (in red).

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
fig, ax = plt.subplots(figsize=(4,4))
ax.set_ylim(-1, 1)
ax.axis('off')
ax.plot(x,y)
fig.savefig("try.png",                   
            #pad_inches=-0.2
            #bbox_inches='tight'
           )
plt.close(fig)

enter image description here

Now, uncommenting the line with #bbox_inches='tight' saves the image without the padding but the saved image is now 237x231 pixels

enter image description here

How to save the image squared without padding?

EDIT Thanks to the answer of @fdireito, after adding fig.subplots_adjust(left=0, right=1, bottom=0, top=1) here is the code that solve both constraints

import numpy as np
import matplotlib.pyplot as plt

x = np.linspace(0, 2 * np.pi, 400)
y = np.sin(x ** 2)
fig, ax = plt.subplots(figsize=(4,4))
ax.set_ylim(-1, 1)
ax.axis('off')
ax.plot(x,y)

fig.subplots_adjust(left=0, right=1, bottom=0, top=1)
fig.savefig("try.png",                   
            #pad_inches=-0.2
            bbox_inches='tight'
           )
plt.close(fig)

Upvotes: 1

Views: 172

Answers (1)

fdireito
fdireito

Reputation: 1729

To remove the padding you mention, you can use:

fig.subplots_adjust(left=0, right=1, bottom=0, top=1)

The numbers above, refer to relative positions of the figure. So, if you set top to 0.5 instead of 1,

fig.subplots_adjust(left=0, right=1, bottom=0, top=0.5)

you will get something like this:

enter image description here

This is, the subplots will, on the left, be at position 0 of the figure, at 1 (max) of the figure on the right, and at 0 in the bottom. Because, in this case, top is set to 0.5, then the top of your curve goes half way in the vertical direction.

See here.

By the way, you may need to set x limits, as well:

ax.set_xlim(min(x),max(x))

Upvotes: 2

Related Questions