0

I am drawing shapes using matplotlib, like that

import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig, ax = plt.subplots(figsize=(4, 4))

ax.tick_params(
    axis  = 'both',
    which = 'both',
    bottom = False,
    top    = False,
    left   = False,
    right  = False,
    labelbottom = False,
    labelleft   = False
    )

ax.patch.set_facecolor('#FFFF99')
ax.add_patch(patches.Rectangle((0.1, 0.1), 0.3, 0.2,
                     facecolor = "green", edgecolor = "black"))
ax.add_patch(patches.Circle((0.5, 0.5), radius = 0.05, facecolor="blue"))

fig.savefig("test.png", bbox_inches='tight')

What I get is

image

The shapes are good, but there is white border outside of the region where I draw shapes; it is not seen on the white background, but it is there.

The question is: How to get rid of this white outer border in the saved file? bbox_inches='tight' does not help.


PS: fig.savefig("test.png", bbox_inches='tight', pad_inches = 0) does the job. Unfortunately it is sort of "too tight", because now I lost bottom and right parts of the axes frame,

image

Probably matplotlib bug (I am using version 3.1.3)

kludg
  • 27,213
  • 5
  • 67
  • 118
  • Can you try `fig.savefig("test.png", bbox_inches='tight', transparent=True)` and see if it works. – Sheldore May 31 '20 at 09:50
  • `transparent=True` makes the outer border transparent; unfortunately, it also makes transparent my background which I created by `ax.patch.set_facecolor('#FFFF99')` – kludg May 31 '20 at 09:57
  • Have you tried a `plt.tight_layout()` call before saving the figure. See also the [Matplotlib tight layout guide](https://matplotlib.org/3.1.3/tutorials/intermediate/tight_layout_guide.html). – 9769953 May 31 '20 at 09:57
  • Did you try this solution [here](https://stackoverflow.com/questions/11837979/removing-white-space-around-a-saved-image-in-matplotlib) – Sheldore May 31 '20 at 09:58
  • `fig.subplots_adjust(left=0,right=1,bottom=0,top=1)` – tmdavison May 31 '20 at 10:04
  • Yep, `fig.savefig("test.png", bbox_inches='tight', pad_inches = 0)` works. Thanks! – kludg May 31 '20 at 10:06

0 Answers0