使用 matplotlib 绘制变化图 [英] Plotting changing graphs with matplotlib

查看:107
本文介绍了使用 matplotlib 绘制变化图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我一直在尝试获取一个图,以通过循环更新每次迭代.我的代码的精简版本如下:

So I have been trying to get a plot to update every iteration through a loop. A stripped down version of my code is as follows:

  1 import matplotlib.pyplot as plt
  2 import numpy as np
  3 
  4 x = np.linspace(0, 9, 10)
  5 for j in range(10):
  6     y = np.random.random(10)
  7     plt.plot(x,y)
  8     plt.show()
  9     plt.pause(1)
 10     plt.clf()

我的问题是我必须在创建下一个图之前关闭每个图;似乎情节卡在 plt.show() 上,而我希望新情节每秒替换当前情节,而无需我的交互.我已经咨询了以下问题:

My issue is that I have to close each plot before the next one is created; it seems like the plot is stuck on plt.show(), whereas I expect a new plot to replace the current one every second without needing my interaction. I've consulted the following questions:

何时使用cla(),clf()或close()用于清除matplotlib中的图?

Python plt:关闭或清除图形不起作用

Matplotlib pyplot show() 关闭后不起作用

但是,所有解决方案似乎都不适合我.任何帮助将不胜感激!

But none of the solutions seemed to work for me. Any help would be appreciated!

推荐答案

您应使用plt.ion()设置交互模式,并使用draw更新

You should set interactive mode with plt.ion(), and use draw to update

import matplotlib.pyplot as plt
import numpy as np

plt.ion()
fig=plt.figure()

x = np.linspace(0, 9, 10)
for j in range(10):
    y = np.random.random(10)
    plt.plot(x,y)
    fig.canvas.draw()
    plt.pause(1)
    plt.clf()

链接至教程

请注意,它可能不适用于所有平台;我在Pythonista/ios上进行了测试,但无法正常工作.

Note that it might not work on all platforms; I tested on Pythonista/ios, which didn't work as expected.

来自

matplotlib 教程

注意交互模式适用于 ipython 和普通 python shell 中的合适后端,但它不适用于 IDLE IDE.如果默认后端不支持交互性,则可以使用什么是后端?"中讨论的任何方法显式激活交互式后端.

Note Interactive mode works with suitable backends in ipython and in the ordinary python shell, but it does not work in the IDLE IDE. If the default backend does not support interactivity, an interactive backend can be explicitly activated using any of the methods discussed in What is a backend?.

这篇关于使用 matplotlib 绘制变化图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆