簡體   English   中英

Matplotlib x 軸動態范圍更新

[英]Matplotlib x-axis dynamic range update

我一直在嘗試使用FuncAnimation創建一個 matplotlib 動畫。

下面的代碼創建了一個簡單的動畫折線圖。

如果這段代碼整天運行(假設它正在跟蹤股票價格),圖表將變得過於加載數據並且根本不可讀。 (見附圖)為了克服這個問題,我試圖如下動態更新 x 軸,以便 x 軸的起點在每次迭代中增加一個值,但我無法讓它工作。

這是導致錯誤的行:

plt.axes().set_xlim([index,100])

以及完整的代碼:

import random
import pandas as pd
import matplotlib.pyplot as plt
from itertools import count
from matplotlib.animation import FuncAnimation

random.seed(234324234234)

x = []
y = []

plt.style.use("fivethirtyeight")

index = count()

def animate(i):
    x.append(next(index))
    y.append(random.randint(0,3))

    plt.cla()
    plt.plot(x,y)
    #plt.axes().set_xlim([index,100])

ani = FuncAnimation(plt.gcf(), animate, interval=1000)

plt.tight_layout()
plt.show()

圖片: 圖片

您可以輕松地通過增加實現這個pyplot.xlim方法給你的函數( pyplot.ylim以及如果需要的話)。 Xlimylim方法用於定義matplotlib pyplot 圖表的軸的下限和上限。

動態更新軸:

如果您使用常量定義xlim參數,您的軸將是固定的,但您的 Python 代碼特別適合使用迭代器i作為xlim的上限值和/或下限值。 例如:

def animate(i):
    x.append(next(index))
    y.append(random.randint(0,3))

    plt.cla()
    plt.plot(x,y)
    plt.xlim(i-20, i+10)

只需調整要減去和添加的值,因為這些值將定義圖表上有關 x 軸的最新數據點前后的邊距。

使用相同的技術,您還可以創建一個動態移動的 y 軸, ylim在您的函數中包含ylim

您可以同時使用上面的示例並將xlim直接應用於xlim ,如下所示:

plt.xlim(i-20, i+10)

您還可以使用軸方法,例如:

axes.set_xlim(i-20, i+10)

來源: 帶有動態軸的 Matplotlib 示例

官方 Matplotlib API 文檔: https ://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.xlim.html

暫無
暫無

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

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