Home > front end >  How to remove whitespace from animated matplotlib GIFs?
How to remove whitespace from animated matplotlib GIFs?

Time:08-31

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

CodePudding user response:

Use subplot_adjust on your figure after creating it.

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

CodePudding user response:

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 enter image description here

  • Related