通过循环迭代更新条形图和子图 [英] Updating bar and plot subplots over loop iterations

查看:120
本文介绍了通过循环迭代更新条形图和子图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写了以下代码段,并试图使其更新图表. 相反,我得到的是新地块与旧地块的重叠. 我研究了一下,发现在当前轴上需要relim()autoscale_view(True,True,True). 我仍然无法获得想要的行为. 有没有办法在调用plt.draw()之前强制pyplot删除/删除旧图形?

I wrote the following snippet and I am trying to make it update the plots. What I get instead is an overlapping of new plots on the old ones. I researched a bit and found I needed relim() and autoscale_view(True,True,True) on the current axis. I still cannot get the desired behaviour. Is there a way to force pyplot to delete/remove the old drawing before calling plt.draw()?

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

plt.ion()
a = np.arange(10)

fig,ax = plt.subplots(2,1)
plt.show()

for i in range(100):
    b = np.arange(10) * np.random.randint(10)
    ax[0].bar(a,b,align='center')
    ax[0].relim()
    ax[0].autoscale_view(True,True,True)
    ax[1].plot(a,b,'r-')
    ax[1].relim()
    ax[1].autoscale_view(True,True,True)
    plt.draw()
    time.sleep(0.01)
    plt.pause(0.001)

推荐答案

轴具有方法clear()来实现这一目标.

Axes has a method clear() to achieve this.

for i in range(100):
    b = np.arange(10) * np.random.randint(10)

    ax[0].clear()
    ax[1].clear()

    ax[0].bar(a,b,align='center')
    # ...

Matplotlib轴文档

但是relim()始终会根据新数据调整尺寸,因此您将获得静态图像.相反,我会使用set_ylim([min, max])设置值的固定区域.

But relim() will always adjust your dimension to the new data so you will get a static image. Instead I would use set_ylim([min, max]) to set a fix area of values.

这篇关于通过循环迭代更新条形图和子图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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