0

I am trying to save GIFs created with matplotlib, but there is too much whitespace surrounding them. I tried passing bbox_inches = "tight" as an argument, but got the following warning:

Warning: discarding the 'bbox_inches' argument in 'savefig_kwargs' as it may cause frame size to vary, which is inappropriate for animation.

Here is a MWE script I am using to generate GIFs:

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation

fig, ax = plt.subplots()

imgs = []
for idx in range(10):
    img = np.random.rand(10, 10)
    img = ax.imshow(img, animated=True)
    imgs.append([img])

anim = ArtistAnimation(fig, imgs, interval=50, blit=True, repeat_delay=1000)
anim.save("test.gif")

Example GIF

Vivek
  • 507
  • 5
  • 15

2 Answers2

1

Use subplot_adjust on your figure after creating it.

fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)
max
  • 677
  • 1
  • 9
  • 34
  • That produces a GIF like this, which is not what I want https://imgur.com/a/gWsEGDb – Vivek Aug 30 '22 at 14:59
  • 1
    This is actually correct, but the figure's size has to be set first so that the `subplots_adjust` knows how to 'fill' the figure. Just adding `fig.set_size_inches(w,h)` somewhere above your `subplots_adjust` call will give the desired results. Also, `wspace=None` and `hspace=None` is not necessary to include (as `None` is the default value) but it is nice to show OP those options – Michael S. Aug 30 '22 at 15:40
1

You need to first set the size of the figure (ex: fig.set_size_inches(5,5)), then turn the axis/grid/etc off (ax.set_axis_off()), then adjust the figure's subplot parameters (fig.subplots_adjust(left=0, bottom=0, right=1, top=1)). Look at the answers to this question for more information.

import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation

fig, ax = plt.subplots()
fig.set_size_inches(5,5)
ax.set_axis_off() # You don't actually need this line as the saved figure will not include the labels, ticks, etc, but I like to include it
fig.subplots_adjust(left=0, bottom=0, right=1, top=1)
imgs = []
for idx in range(10):
    img = np.random.rand(10, 10)
    img = ax.imshow(img, animated=True)
    imgs.append([img])
anim = ArtistAnimation(fig, imgs, interval=50, blit=True, repeat_delay=1000)
anim.save("test.gif")

Borderless Gif:

enter image description here

Michael S.
  • 3,050
  • 4
  • 19
  • 34