在 matplotlib 中绘制最后 100 个点

Plot the last 100 points in matplotlib

以下 gif 是使用 gnuplot 和 Fortran 创建的。但是,现在我只想使用 Python(主要是动画形式 matplotlib)来做同样的事情。

我可以用 Python 生成一个 gif,但我不知道如何生成类似右侧 gif 的东西(你也绘制了最后 100 个点),阶段的演变 space .

我们将不胜感激,

谢谢

gif 的 Gnuplot 代码:

set term gif size 1000,600 animate  delay 1000 loop 0 
set output "animacio.gif"
cd 'C:\Users\Usuario\Desktop'
datafile ="P7-1718-b-res.dat" 


do for[i=1:5000:10]{

set multiplot

set size 0.5,0.8
set origin 0.0,0.0
set title "Evolució de l'angle girat i velocitat angular (t)"
set xrange[0:50]
set yrange[-pi:pi]
set xlabel "t (s)"
set ylabel "Angle girat, v_{ang}"
set key below
plot datafile index 9 every ::1::i with line linewidth 4 t"Posició angular" ,datafile index 9 every ::1::i u 1:3 with line linewidth 4 t"V_{ang}"

set origin 0.5,0
set size 0.5,0.8
set title "Evolució en l'espai de fases"
set yrange[-pi:pi]
set xrange[-pi:pi]
set xlabel "Angle girat(rad)"
set ylabel "Velocitat angular(rad/s)"
set key below
if (i>101) { 
plot datafile index 9 every::i::i u 2:3 t"" ps 3,datafile index 9 every::i-100::i u 2:3 w l t"" } 
else {
plot datafile index 9 every::i::i u 2:3 t"" ps 3}
unset multiplot
}

并假设您的数据在索引 9 处有三行(时间、位置、angular 速度)。

正如您所说,您可以使用 Matplotlib 动画来实现它。

我对你的数据做了一些"similar",当然,因为我没有得到数据文件,所以不等于。代码如下:

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

w = 1.
t = np.linspace(0,10,200)
x = np.cos(w*t)
v = -w*np.cos(w*t)

fig, ax = plt.subplots(1,2)

line_1, = ax[0].plot([], [], 'b-', lw=2)
line_2, = ax[0].plot([], [], 'r-', lw=2)
ax[0].set_xlim([0,50])
ax[0].set_ylim([-np.pi,np.pi])

line_3, = ax[1].plot([], [], 'g-', lw=2)
star_3, = ax[1].plot([], [], 'g*')
ax[1].set_xlim([-np.pi,np.pi])
ax[1].set_ylim([-np.pi,np.pi])

def animate(i):
    line_1.set_data(t[:i],x[:i])  # update the data
    line_2.set_data(t[:i],v[:i])
    nLast = 20
    idFrom = i-nLast if(i-nLast >= 0) else 0
    line_3.set_data(np.cos(t[idFrom:i+1]),np.sin(t[idFrom:i+1]))
    star_3.set_data(np.cos(t[i]),np.sin(t[i]))
    return line_1,line_2,line_3,star_3

# Init only required for blitting to give a clean slate.
def init():
    line_1.set_data([], [])
    line_2.set_data([], [])
    line_3.set_data([], [])
    star_3.set_data([], [])
    return line_1,line_2,line_3,star_3

anim = animation.FuncAnimation(fig, animate, np.arange(1, len(t)), init_func=init, interval=100, blit=True)
#anim.save('Plot_last_nLast.mp4', fps=15)
#anim.save('Plot_last_nLast.gif', dpi=80, writer='imagemagick')
plt.show()

您可以将动画保存为 GIF(需要 Imagemagick)或作为 MP4 电影,如果您有 ffmpeg 将其用作动画的作者。 但那是另一个问题