生成重复更新图(FuncAnimation - Matplotlib)

Generating repeatedly updating graph (FuncAnimation - Matplotlib)

我正在尝试编写一个代码,该代码将生成一个被反复更新并具有双轴(2 个 y 轴,共享相同的 x 轴)的图形。

当我不将它与 FuncAnimation 结合使用时,该代码运行良好,但是当我尝试这样做时,我得到一个空图。


def animate(i):
    data=prices(a,b,c)    #function that gives a DataFrame with 2 columns and index
    plt.cla()   
    fig=plt.figure()
    ax = fig.add_subplot(111)
    ax.plot(data.index, data.value1)
    ax2 = ax.twinx()
    ax2.plot(data.index, data.value2)
    plt.gcf().autofmt_xdate()     
    plt.tight_layout()  

call = FuncAnimation(plt.gcf(), animate, 1000)  
plt.tight_layout()
plt.show
'''


I believe the error is in "call". Unfortunately, I don't know FuncAnimation so well.

您可以尝试这样的操作:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd
from datetime import datetime, timedelta

def getPrices(i):
    return pd.DataFrame(index=[datetime.now() + timedelta(hours=i) for i in range(10)], data={'value1':range(10), 'value2':[(x + i) % 5 for x in range(10)]})

def doAnimation():
    fig=plt.figure()
    ax = fig.add_subplot(111)

    def animate(i):
        #data=prices(a,b,c)    #function that gives a DataFrame with 2 columns and index
        data = getPrices(i)

        plt.cla()
        ax.plot(data.index, data.value1)
        ax2 = ax.twinx()
        ax2.plot(data.index, data.value2)
        plt.gcf().autofmt_xdate()     
        plt.tight_layout()  
        return ax, ax2

    call = FuncAnimation(plt.gcf(), animate, 1000)  
    plt.show()

doAnimation()

更新:

虽然这在我的环境中有效,但评论中的 OP 表示它不起作用并引发以下警告:

UserWarning: Animation was deleted without rendering anything. This is most likely not intended. To prevent deletion, assign the Animation to a variable, e.g. anim, that exists until you have outputted the Animation using plt.show() or anim.save()

由于 plt.show() 在调用 FuncAnimation() 之后立即被调用,这令人费解,但以下内容可能有助于确保 Animation 不会被过早删除:

import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import pandas as pd
from datetime import datetime, timedelta

def getPrices(i):
    return pd.DataFrame(index=[datetime.now() + timedelta(hours=i) for i in range(10)], data={'value1':range(10), 'value2':[(x + i) % 5 for x in range(10)]})

def doAnimation():
    fig=plt.figure()
    ax = fig.add_subplot(111)

    def animate(i):
        #data=prices(a,b,c)    #function that gives a DataFrame with 2 columns and index
        data = getPrices(i)

        plt.cla()
        ax.plot(data.index, data.value1)
        ax2 = ax.twinx()
        ax2.plot(data.index, data.value2)
        plt.gcf().autofmt_xdate()     
        plt.tight_layout()  
        return ax, ax2

    call = FuncAnimation(plt.gcf(), animate, 1000)  
    return call

callSave = doAnimation()
plt.show()