Matplotlib.animation: how to remove white margin

I searched all day for this and ended up using this solution from @matehat when creating each image.

import matplotlib.pyplot as plt
import matplotlib.animation as animation

To make a figure without the frame :

fig = plt.figure(frameon=False)
fig.set_size_inches(w,h)

To make the content fill the whole figure

ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()
fig.add_axes(ax)

Draw the first frame, assuming your movie is stored in 'imageStack':

movieImage = ax.imshow(imageStack[0], aspect='auto')

I then wrote an animation function:

def animate(i):
    movieImage.set_array(imageStack[i])
    return movieImage

anim = animation.FuncAnimation(fig,animate,frames=len(imageStack),interval=100)
anim.save('myMovie.mp4',fps=20,extra_args=['-vcodec','libx264']

It worked beautifully!

Here is the link to the whitespace removal solution:

1: remove whitespace from image


Passing None as an arguement to subplots_adjust does not do what you think it does (doc). It means 'use the deault value'. To do what you want use the following instead:

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

You can also make your code much more efficent if you re-use your ImageAxes object

mat = np.random.random((100,100))
im = ax.imshow(mat,interpolation='nearest')
with writer.saving(fig, "writer_test.mp4", 100):
    for i in range(100):
        mat = np.random.random((100,100))
        im.set_data(mat)
        writer.grab_frame()

By default imshow fixes the aspect ratio to be equal, that is so your pixels are square. You either need to re-size your figure to be the same aspect ratio as your images:

fig.set_size_inches(w, h, forward=True)

or tell imshow to use an arbitrary aspect ratio

im = ax.imshow(..., aspect='auto')