【问题标题】:Updating bar and plot subplots over loop iterations通过循环迭代更新条形图和绘图子图
【发布时间】:2016-06-21 00:17:01
【问题描述】:

我写了以下 sn-p 并试图让它更新情节。 相反,我得到的是旧地块上新地块的重叠。 我研究了一下,发现当前轴上需要relim() 和autoscale_view(True,True,True)。 我仍然无法获得所需的行为。 有没有办法在调用 plt.draw() 之前强制 pyplot 删除/移除旧绘图?

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)

【问题讨论】:

    标签: python loops matplotlib subplot


    【解决方案1】:

    Axes 有一个方法clear() 来实现这一点。

    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 Axes Documentation

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

    【讨论】:

      【解决方案2】:

      无需重置坐标区限制或使用 relim,您可能只想更新条形高度。

      import numpy as np
      import matplotlib.pyplot as plt
      
      plt.ion()
      a = np.arange(10)
      
      fig,ax = plt.subplots(2,1)
      plt.show()
      
      b = 10 * np.random.randint(0,10,size=10)
      rects = ax[0].bar(a,b, align='center')
      line, = ax[1].plot(a,b,'r-')
      ax[0].set_ylim(0,100)
      ax[1].set_ylim(0,100)
      
      for i in range(100):
          b = 10 * np.random.randint(0,10,size=10)
          for rect, h in zip(rects, b):
              rect.set_height(h)
          line.set_data(a,b)
          plt.draw()
          plt.pause(0.02)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-09-06
        • 2021-09-20
        • 2016-11-22
        • 1970-01-01
        • 2014-05-30
        • 2019-05-28
        • 1970-01-01
        • 2022-11-10
        相关资源
        最近更新 更多