Matplotlib返回空图

5 python animation matplotlib spyder

我有这个python代码:

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

n = 100
x = np.random.randn(n)

def update(curr):
    if curr == n:
        a.event_source.stop()
    plt.cla()
    bins = np.arange(-4,4,0.5)
    plt.hist(x[:curr],bins = bins)
    plt.gca().set_title('Samplng the Normal distribution')
    plt.gca().set_ylabel('Frequency')
    plt.gca().set_xlabel('Value')
    plt.annotate('n = {}'.format(curr), [3,27])

fig = plt.figure()
a = animation.FuncAnimation(fig, update, interval = 100)
Run Code Online (Sandbox Code Playgroud)

它应该每3次绘制更新​​一次正态分布图,但是当我运行它时,我的情节是空的,没有任何反应.你知道为什么吗?

谢谢!

Imp*_*est 3

问题中的代码是完美的。它每 100 毫秒更新一次绘图。

我的猜测如下。事实上,您没有plt.show()在此处使用,但仍然看到一个绘图,这表明您正在内联环境中使用它。例如,您可能正在使用 Jupyter 并且(有意或无意)已经激活了%matplotlib inline. 内联后端不支持动画(这一点很明显,因为它只显示绘图的 png 图像),因此解决方案可能是使用不同的后端。

如果在 jupyter 笔记本中:

  • 如果您想在笔记本中显示动画,请使用%matplotlib notebook.
  • 如果您想在笔记本中使用动画并使用%matplotlib inline matplotlib 2.1 或更高版本,您也可以使用 from

    IPython.display import HTML
    HTML(ani.to_jshtml())
    
    Run Code Online (Sandbox Code Playgroud)

    显示动画。

  • 如果您想将动画作为它自己的窗口,请使用%matplotlib tk.

如果将代码作为脚本运行:

  • 添加plt.show()在代码末尾。

如果在spyder中运行

  • 确保您没有在内置 IPython 控制台中运行代码。而是在新的专用 python 控制台中运行它。
    在此输入图像描述