Matplotlib returns 空图

Matplotlib returns empty plot

我有这个 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)

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

谢谢!

你错过了最后的 plt.show()。这条指令对我有用。

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

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

如果在 jupyter notebook 中:

  • 如果你想在笔记本里面有动画,使用%matplotlib notebook
  • 如果你想在笔记本里面有动画 and 使用 %matplotlib inline and 有 matplotlib 2.1 或更高版本,您也可以使用 from

    IPython.display import HTML
    HTML(ani.to_jshtml())
    

    显示动画。

  • 如果你想拥有自己的动画 window,请使用 %matplotlib tk

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

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

如果运行宁在spyder

  • 确保您没有在内置 IPython 控制台中 运行 运行代码。相反 运行 它在一个新的专用 python 控制台中。