In a Google Colab notebook, I'm building a matplotlib animation and I'm displaying it as HTML5 video. The last lines of my script are:
# ...
anim = animation.ArtistAnimation(plt.gcf(), frames,
interval=250, blit=True, repeat=False)
HTML(anim.to_html5_video())
The video looks alright, but then I get another image of the plot displayed below the video (showing the same thing as the last frame of the video). If I call plt.close()
at the end, neither the plot nor the video gets displayed. How can I show the video without showing the plot?
Short answer: call plt.close()
to avoid displaying the static image.
Jupyter notebooks (including Colab) will automatically show any matplotlib image created in a cell, regardless of explicit print or display statements in the cell. You can see this by running
plt.plot([1, 2, 3])
print('done')
The cell output will contain both the implicitly-displayed chart, and the explicitly-displayed text.
You can prevent this implicit display by closing the chart before the end of the cell:
plt.plot([1, 2, 3])
plt.close()
print('done')
In your case, you want to display an HTML animation built from the chart, but not the chart itself. It would look like this:
anim = animation.ArtistAnimation(plt.gcf(), frames,
interval=250, blit=True, repeat=False)
plt.close()
HTML(anim.to_html5_video())