matplotlib/seabornで日本語表示させる簡単な方法(文字化けを治す方法)
tadanori
Aru's テクログ(Aruaru0)
matplitlib.animation
を使うと、グラフをアニメーションさせることができますが、Google Colab上ではそのままではアニメーションできません。ここでは、Google Colab上でグラフをアニメーションさせる方法について解説します。
Jupyter notebookの場合、matplotlib.animation
をインポートした後に以下のマジックコマンドを追加することでアニメーションを追加することが可能です。
%matplotlib nbagg
ただ、Google Colabではnbaggを設定しただけではアニメーションできません。
これに加えて以下のコードでjavascriptでアニメーションさせるように設定する必要があります
from matplotlib import animation, rc
rc('animation', html='jshtml')
上記の2つをおまじないと思って記述しておけばOKです
Google Colabでアニメーションさせたい場合は、以下のコードを最初にいれておけばOK
from matplotlib import animation, rc
%matplotlib nbagg
rc('animation', html='jshtml')
animation.ArtistAnimation
最初にplt.plot
で複数のグラフを作成しておき、これをアニメーションされる例です。
animation.ArtistAnimation
を利用してアニメーションを生成させます。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, rc
%matplotlib nbagg
rc('animation', html='jshtml')
fig = plt.figure()
ims = []
rand = np.random.randn(1000)
for i in range(10):
im = plt.plot(rand[i*10:900+i*10],'b')
ims.append(im)
ani = animation.ArtistAnimation(fig, ims,interval=100)
ani
表示は以下のようになります。
アニメーションは以下のようになります
また、アニメーションは、以下のコードでgifファイルとして保存できます
ani.save("xxx.gif")
animation.FuncAnimation
動的にデータを生成する例です。
表示するデータを作成する関数(例ではplot()
)を作成しておき、呼び出します。
動的に生成する場合はanimation.FuncAnimation
を利用してアニメーションを生成します。
Colabで表示させるには、何フレーム(何枚)の画像を生成させるかを指定する引数frames
を指定する必要があります。
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import animation, rc
%matplotlib nbagg
rc('animation', html='jshtml')
v = np.random.randn(200)
def plot(data):
plt.cla()
plt.plot(v[data: data+100])
plt.tick_params(
axis='x',
which='both',
bottom=True,
top=False,
labelbottom=False)
fig = plt.figure()
ani = animation.FuncAnimation(fig, plot, interval=10, frames=100)
ani
Google Colabでアニメーションを表示させようとしてハマりましたので記事にしました。