[英]How to show a matplotlib animation in Colab without also showing the plot?
In a Google Colab notebook, I'm building a matplotlib animation and I'm displaying it as HTML5 video.在 Google Colab 笔记本中,我正在构建一个 matplotlib 动画并将其显示为 HTML5 视频。 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.如果我在最后调用plt.close()
,则不会显示情节和视频。 How can I show the video without showing the plot?如何在不显示情节的情况下显示视频?
Short answer: call plt.close()
to avoid displaying the static image.简短回答:调用plt.close()
以避免显示静态图像。
Jupyter notebooks (including Colab) will automatically show any matplotlib image created in a cell, regardless of explicit print or display statements in the cell. Jupyter 笔记本(包括 Colab)将自动显示在单元格中创建的任何 matplotlib 图像,无论单元格中的显式打印或显示语句如何。 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.在您的情况下,您希望显示从图表构建的 HTML 动画,而不是图表本身。 It would look like this:它看起来像这样:
anim = animation.ArtistAnimation(plt.gcf(), frames,
interval=250, blit=True, repeat=False)
plt.close()
HTML(anim.to_html5_video())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.