我正試圖繪制在運行時生成的資料。為了做到這一點,我使用了matplotlib.animation.FuncAnimation.
雖然資料顯示正確,但軸的值卻沒有根據顯示的值進行相應的更新:
盡管我在update_line函式中的每一次迭代中都對其進行了更新,但x軸顯示的數值還是從0到10(見以下代碼)。
DataSource包含資料向量,并在運行時追加數值,同時還回傳被回傳的數值的索引:
import numpy as np
class DataSource:
資料 = []
display = 10: data = [] display = 10.
# 附加一個亂數并回傳最后10個值。
def getData(self)。
self.data.append(np.random.rand(1)[0])
if(len(self.data) <= self.display)。
return self.data。
else:
return self.data[-self.display:].
# return the index of the last 10 values.
def getIndexVector(self)。
if(len(self.data) <= self.display)。
return list(range(len(self.data))
else:
return list(range(len(self.data))[-self.display:] 。]
我從matplotlib檔案中獲得了plot_animation函式。
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
from datasource import DataSource
def update_line(num, source, line)。
data = source.getData()
indexs = source.getIndexVector()
if indexs[0] != 0:
plt.xlim(indexs[0], indexs[-1])
dim=np.range(indexs[0],indexs[-1], 1)
plt.xticks(dim)
line.set_data(indexs,data)
return line,
def plot_animation()。
fig1 = plt.figure()
source = DataSource()
l, = plt.plot([], [], 'r-')
plt.xlim(0, 10)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
line_ani = animation.FuncAnimation(fig1, update_line, fargs=(source, l),
interval=150, blit=True)
# 要保存影片,使用命令:line_ani.save('lines.mp4')
plt.show()
if __name__ == "__main__"/span>:
plot_animation()
我怎樣才能在影片的每個迭代中更新x軸的值呢?
(如果你看到任何錯誤,我很感謝你提出的改進代碼的建議,盡管它們可能與問題無關)。
uj5u.com熱心網友回復:
解決方案
我的問題出在以下一行:line_ani = animation.FuncAnimation(fig1, update_line, fargs=(source, l),
interval=150, blit=True)
我所要做的是改變選項blit=False,然后X軸就開始按要求移動了。
uj5u.com熱心網友回復:
下面是一個簡單的案例,你可以實作這一點。
importmatplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np
%matplotlib筆記本
#data generator[/span
data = np.random.random((100, ))
#setup figure[/span].
fig = plt.fig(figsize=(5,4)
ax = fig.add_subplot(1,1, 1)
#rolling window size
repeat_length =25
ax.set_xlim([0, repeat_length])
ax.set_ylim([-2,2] )
#set figure to be modified[/span]。
im, = ax.plot([], [])
def func(n)。
im.set_xdata(np.arange(n))
im.set_ydata(data[0:n])
if n> repeat_length:
lim = ax.set_xlim(n-repeat_length, n)
else:
lim = ax.set_xlim(0, repeat_length)
return im
ani = animation.FuncAnimation(fig, func, frames=data.shape[0], interval=30, blit=False)
plt.show()
#ani.save('animation.gif',writer=' pillow', fps=30)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/312372.html
標籤:

