我正在嘗試撰寫一個代碼,該代碼將生成一個重復更新并具有雙軸(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.
uj5u.com熱心網友回復:
你可以嘗試這樣的事情:
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:影片被洗掉而沒有渲染任何東西。這很可能不是故意的。為防止洗掉,請將影片分配給一個變數,例如 anim,該變數在您使用 plt.show() 或 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()
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/485446.html
標籤:Python matplotlib 动画 jupyter-笔记本
上一篇:僅使用CSS的文本向上滑動影片
下一篇:如何將中心的邊框影片與文本對齊
