Vivek
Vivek

Reputation: 569

How to remove whitespace from animated matplotlib GIFs?

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

Upvotes: 1

Views: 854

Answers (2)

Michael S.
Michael S.

Reputation: 3128

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

Upvotes: 2

max
max

Reputation: 686

Use subplot_adjust on your figure after creating it.

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

Upvotes: 1

Related Questions