【问题标题】:Matplotlib returns empty plotMatplotlib 返回空图
【发布时间】:2017-11-20 15:09:15
【问题描述】:

我有这个 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 次绘制更新​​一次正态分布图,但是当我运行它时,我的图是空的,没有任何反应。你知道为什么吗?

谢谢!

【问题讨论】:

    标签: python animation matplotlib spyder


    【解决方案1】:

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

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

    如果在 jupyter 笔记本中:

    • 如果您想在笔记本中添加动画,请使用%matplotlib notebook
    • 如果你想在 notebook 中添加动画并且使用%matplotlib inline并且有matplotlib 2.1或更高版本,你也可以使用from

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

      显示动画。

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

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

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

    如果在 spyder 中运行

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

    【讨论】:

    • 我认为它实际上是后端,你是对的。我将其更改为自动,现在可以使用。谢谢!
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2022-11-12
      • 2017-08-21
      • 2017-02-14
      • 2017-10-11
      • 1970-01-01
      • 2021-07-13
      • 1970-01-01
      • 2015-10-03
      • 1970-01-01
      相关资源
      最近更新 更多