0

I would like to use plt.imshow without a large white margin around the image. Here is an example:

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(8, 8)
plt.imshow(data, origin='lower', interpolation='None', aspect='equal')
plt.axis('off')
plt.show()

and viewer window produced:

enter image description here

How to reduce the white space margin around the image?

This is not the same question as matplotlib.pyplot.imshow: removing white space within plots when using attributes "sharex" and "sharey". I tried suggestions from there to no effect.

Paul Jurczak
  • 7,008
  • 3
  • 47
  • 72
  • 3
    `plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)`. See e.g. [this post](https://stackoverflow.com/questions/11837979/removing-white-space-around-a-saved-image) – JohanC Feb 16 '22 at 21:46
  • @JohanC Great! This actually fills all available window pane. If you post it as an answer, I will accept it as a solution. – Paul Jurczak Feb 16 '22 at 21:51

1 Answers1

3

Using matplotlib.pyplot.tight_layout() may solve your problem.

import matplotlib.pyplot as plt
import numpy as np

data = np.random.rand(8, 8)
plt.imshow(data, origin='lower', interpolation='None', aspect='equal')
plt.axis('off')
plt.tight_layout()
plt.show()

tight layout exemple

arthropode
  • 1,361
  • 2
  • 12
  • 19
  • Thank you, it works nicely. The comment above with `plt.subplots_adjust(top = 1, bottom = 0, right = 1, left = 0, hspace = 0, wspace = 0)` fills the window even better. – Paul Jurczak Feb 16 '22 at 21:53
  • The command given by @PaulJurczak is the actual solution. I was able to get rid of white background only with this command. Thank you very much! – Prabath Apr 13 '23 at 01:29