簡體   English   中英

Matplotlib 動畫:如何動態擴展 x 限制?

[英]Matplotlib Animation: how to dynamically extend x limits?

我有一個簡單的動畫情節,如下所示:

import numpy as np
from matplotlib import pyplot as plt
from matplotlib import animation

# First set up the figure, the axis, and the plot element we want to animate
fig = plt.figure()
ax = plt.axes(xlim=(0, 100), ylim=(0, 100))
line, = ax.plot([], [], lw=2)

x = []
y = []


# initialization function: plot the background of each frame
def init():
    line.set_data([], [])
    return line,


# animation function.  This is called sequentially
def animate(i):
    x.append(i + 1)
    y.append(10)
    line.set_data(x, y)
    return line,


# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=200, interval=20, blit=True)

plt.show()

現在,這可以正常工作,但我希望它像http://www.roboticslab.ca/matplotlib-animation/中的子圖之一一樣擴展,其中 x 軸動態擴展以容納傳入的數據點。

我該如何實現?

我遇到了這個問題(但對於 set_ylim)並且我對@ImportanceOfBeingErnest 的評論進行了一些試驗和錯誤,這就是我得到的,適用於@nz_21 問題。

def animate(i):
    x.append(i + 1)
    y.append(10)
    ax.set_xlim(min(x), max(x)) #added ax attribute here
    line.set_data(x, y)

    return line, 

# call the animator.  blit=True means only re-draw the parts that have changed.
anim = animation.FuncAnimation(fig, animate, init_func=init,
                               frames=500, interval=20)

實際上在@nz_21 引用的網絡中,有一個類似的解決方案。

如果您向畫布發送調整大小事件,強制 MPL 刷新畫布,即使blit=True也有解決方法。 需要明確的是,@ffffff 答案中的代碼不適用於 blit 是 MPL 代碼庫中的一個錯誤,但是如果您在設置新的 x 軸后添加fig.canvas.resize_event() ,它將在MPL 3.1.3。 當然,您應該只是偶爾這樣做才能真正從 blitting 中獲得任何好處——如果您每幀都這樣做,那么無論如何您只是在執行非 blit 過程,但需要額外的步驟。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM