【问题标题】:Plot the last 100 points in matplotlib在 matplotlib 中绘制最后 100 个点
【发布时间】:2018-08-07 13:51:24
【问题描述】:

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

我可以使用 Python 生成 gif,但我不知道如何生成类似右侧 gif(您还绘制最后 100 个点)之类的东西,即相空间中的演变。

我们将不胜感激,

谢谢

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 处有三行(时间、位置、角速度)。

【问题讨论】:

  • 你需要显示你用来绘制这些的代码。
  • 虽然您可能很幸运,在这种情况下有人可以将您的完整代码翻译成其他语言,但通常需要将您的问题限制在特定问题上;这意味着显示您遇到问题的 python 代码,并明确说明您需要帮助的地方。

标签: python animation matplotlib gif


【解决方案1】:

正如您所提到的,您可以使用 Matplotlib 动画来使其工作。

我做了一些与您的数据“相似”的事情,但是当然,由于我没有数据文件,所以它不相等。代码如下:

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()

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

【讨论】:

    猜你喜欢
    • 2011-01-19
    • 2017-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多