3

I'd like to plot a NumPy array using imshow in matplotlib and save it as a JPEG image. However, I can't manage to remove margins/paddings/borders from the image.

My code:

plt.imshow(np.arange(20).reshape(5,4)) ;
plt.axis('off')
plt.savefig('test.jpg', bbox_inches='tight', pad_inches=0, facecolor='black')

I've followed all recommendations that I could find here on Stackoverflow but none of them would help removing uneven white borders (I made them black in this figure) seen below:

enter image description here

John Manak
  • 13,328
  • 29
  • 78
  • 119
  • did answer #1 solve your problem? – welch Mar 31 '16 at 21:58
  • Possible duplicate of [Removing white space around a saved image in matplotlib](https://stackoverflow.com/questions/11837979/removing-white-space-around-a-saved-image-in-matplotlib) – thedoctar Oct 25 '19 at 11:59
  • Answer is here: https://stackoverflow.com/questions/11837979/removing-white-space-around-a-saved-image-in-matplotlib/27227718 – thedoctar Oct 25 '19 at 11:59

2 Answers2

0

setting pad_inches = -1 solved this for me (saving as png).

I suspect the pad_inches=0 was being interpreted as "falsey" and ignored

welch
  • 936
  • 8
  • 12
0

As it was described in this answer: https://stackoverflow.com/a/26610602/265289, it's important to also call:

fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)

alongside pad_inches=0. This removes the extra space to the left and bottom of the image.

Community
  • 1
  • 1
John Manak
  • 13,328
  • 29
  • 78
  • 119