2017-05-12 10 views
1

現在、パンダデータフレームに保存されている月次データの散布図をアニメーション化しようとしています。今まで私はループを作りました。今、私はそれらを1つのgif(または私は気にしないmp4)に参加させたいと思っています。 mathplotlibsアニメーション関数を使用する簡単な方法はありますか?私はFuncAnimationを介してスライスされたデータをどのようにループするか、私の周りに頭を浮かべることはできません。これまでのところ、私はこれをしなかった:matplotlibでパンダデータの散布図をアニメートする方法

time = df.monat.unique() 
for i in time: 
    dft = df[(df.monat == i) & (df.xcol < 4000)] 
    plt.scatter(x=dft['xcol'], 
      y=dft['ycol'], 
      s=dft['scol']/25, 
      c=dft['clr'], 
      linewidth=0, 
      alpha=0.8) 
    plt.title('Title ' + str(i), fontsize=10) 
    plt.xlabel('x label', fontsize=9) 
    plt.ylabel('y label', fontsize=9) 
    legend1_line2d = list() 
    for val in clrdict.values(): 
     legend1_line2d.append(mlines.Line2D([0], [0], 
      linestyle='none', 
      marker='o', 
      alpha=0.6, 
      markersize=6, 
      markeredgecolor=None, 
      markeredgewidth=0, 
      markerfacecolor=val)) 
    legend1 = plt.legend(legend1_line2d, 
      names, 
      frameon=False, 
      numpoints=1, 
      fontsize=8, 
      loc='upper right') 
    plt.show() 

答えて

0

は、私が自分でそれを考え出し:

が空のプロット(図)を生成します。前と同じように、すべてのユニークな時間値は一連の(時間)に格納されます。単純なカウンタ(i)は、update関数内の各月のデータ(dft)の正確なスライス(df.monat ==系列の時刻からの値)を生成するのに役立ちます。 update-functionは、anim.FuncAnimation(frames = len(time))内のframe-parameterの値を掛けて呼び出されます。

希望、これは(私が見つけたmatplotlibのをFuncAnimationについての説明のほとんどは、乱数で働いた - いない特定のパンダの列に)他の誰かのために役に立ちます。

import pandas as pd 
import matplotlib.pyplot as plt 
import matplotlib.lines as mlines 
import matplotlib.animation as anim 

... 

time = df.monat.unique()  
fig = plt.figure() 
i = 1 

def update(i): 
     plt.clf() 
     dft = df[(df.monat == time[i]) & (df.xcol < 4000)] 
     plt.scatter(x=dft['xcol'], 
        y=dft['ycol'], 
        s=dft['scol']/25, 
        c=dft['clr'], 
        linewidth=0, 
        alpha=0.8) 
     plt.title('Title ' + str(time[i]), fontsize=10) 
     plt.xlabel('x label', fontsize=9) 
     plt.ylabel('y label', fontsize=9) 
     plt.xlim(0, 900) # fixed dimensions x 
     plt.ylim(-5, 100) # fixed dimensions y 
     legend1_line2d = list() 
     for val in clrdict.values(): 
      legend1_line2d.append(mlines.Line2D([0], [0], 
        linestyle='none', 
        marker='o', 
        alpha=0.6, 
        markersize=6, 
        markeredgecolor=None, 
        markeredgewidth=0, 
        markerfacecolor=val)) 
     legend1 = plt.legend(legend1_line2d, 
        names, 
        frameon=False, 
        numpoints=1, 
        fontsize=8, 
        loc='upper right') 
     i += 1 

ani = anim.FuncAnimation(fig, update, frames=len(time), interval=500) 
# plt.show() # this will show the ani over and over 
ani.save("test.mp4", dpi=200, fps=1, codec="libx264", bitrate=5000, extra_args=['-pix_fmt', 'yuv420p'])