LoginSignup
0
0

matplotで粒径を指定してアニメーションをつくる

Last updated at Posted at 2023-06-14

粒子配置が連番ファイルで与えられているとして、matplotでそれをアニメーションにしたい。
粒子の大きさを気にすることなく、ただプロットするだけならplot関数(色をつけたいならscatter関数)を使えば良い。
plotを使う場合→matplotlibで連番ファイルからgifアニメを作る
アニメーションの基本的なことはこの記事が参考になる。

座標を単位として粒径を設定するためにEllipseCollection関数を使う。
(円専用のCircleCollection関数も存在するが、そちらは粒径の設定方法が面倒なので今回は使わない)

import matplotlib
from matplotlib.animation import FuncAnimation
from matplotlib.collections import EllipseCollection
import numpy as np
import matplotlib.pyplot as plt

%matplotlib inline
%config InlineBackend.figure_format = 'retina'
L = 10.0
filenum = 20  # number of files
fig = plt.figure(figsize=(12, 12))
ax = fig.add_subplot(1, 1, 1)
ax.set_aspect("equal")
#  ax = fig.add_subplot("14{}".format(j))
x, y, a = np.loadtxt("file_path_10.dat", comments='#', unpack=True)
title = plt.title("t")
plt.xlim(0, L)
plt.ylim(0, L)
p = EllipseCollection(a, a, a, units="xy", cmap=matplotlib.cm.jet,transOffset=ax.transData, alpha=1.0, fc='g', ec="k", lw=0.5,offsets=np.column_stack([x, y]),animation=True)
ax.add_collection(p)
plt.xlabel(r"$x$", color='k', size=35)
plt.ylabel(r"$y$", color='k', size=35)
def init():
    pass
def update_anim(j):
    x, y, a = np.loadtxt("file_path_{:n}.dat".format( j), comments='#', unpack=True)
    p.set_offsets(np.column_stack([x, y]))
    p.set_array(x)  # colors of each particles.
    title.set_text("t={:.1f}".format( j*5))
    return [p]
ani = FuncAnimation(fig, update_anim, init_func=init(),interval=150, blit=True, frames=filenum)
ani.save("anime.mp4",writer="ffmpeg")
plt.show()

anime_1.gif

各関数の説明

Funkanimationについて

こちらの記事が詳しい→matplotlibのanimation.FuncAnimationを用いて柔軟にアニメーション作成

builtのオプションはupdate_anim関数の返値があるかどうかを決めている。Trueの方が早いらしい。

EllipseCollectionについて

matplotの公式ドキュメント
多くの楕円を描くための関数。
第1-3引数:それぞれの粒子の長軸の長さ、短軸の長さ、なす角 を表す。ここでは円を描くため、長軸、短軸の長さは共に1、なす角は適当な配列にしてある。楕円を描く場合、なす角の単位は度でラジアンでないため注意すること
units="xy":粒径の単位。ここではxy座標
transOffset=ax.transData:座標の単位?ここではxy座標
cmap=matplotlib.cm.jet, fc='g', ec="k", lw=0.5:cmap,粒子の色、縁の色、縁の線幅
offsets=np.column_stack([x, y]):各粒子の座標。[[x1,y1][x2,y2]…]という形式で入れる。
animated=True プロットされ託するオプション。built=Trueと組み合わせることでプログラムが早くなる

update_animの中身

set_offsets:粒子の座標を入れる。形式はoffsetsのときと一緒
set_array:粒子の色を決めるパラメータ。上下限はset_climで設定可能

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0