using Base64
linspace(start, stop, length) = range(start, stop=stop, length=length)
using PyPlot
using PyCall
@pyimport matplotlib.animation as anim
using Distributions
function showgif(filename)
open(filename) do f
base64_video = base64encode(f)
display("text/html", """<img src="data:image/gif;base64,$base64_video">""")
end
end
function plotchisqsim(df)
N = 10^4
chisq = rand(Chisq(df),10^4)
x = linspace(0.1, df + 4*sqrt(2df), 100)
f(x) = pdf(Chisq(df),x)
clf()
title("rand(Chisq($df),$N) vs. pdf(Chisq($df),x)")
plt[:hist](chisq, range=(0, df + 4*sqrt(2df)), bins=50, normed=true, label="rand")
plot(x, f.(x), label="pdf")
legend()
xlabel("value of \$\\chi^2\$")
ylabel("probability density")
grid(true)
plot()
end
file = "chisqsim.gif"
######### Construct Figure and Plot Data
fig = figure(figsize=(6.4,4.8))
# Create the animation object by anim.FuncAnimaton
frames = [1;1;1:30;29:-1:2]
@time myanim = anim.FuncAnimation(fig, plotchisqsim, frames=frames, interval=100)
# Convert it to an animated GIF file by Imagemagick.
@time myanim[:save](file, writer="imagemagick")
sleep(0.2)
# Display the movie in a Julia cell as follows.
showgif(file)
# Don't display the axes of figure().
clf()
0.554325 seconds (1.24 M allocations: 62.523 MiB, 3.45% gc time) 25.420036 seconds (4.94 M allocations: 228.204 MiB, 0.33% gc time)
PyPlot は Python の matplotlib.pyplot を使って作画するためのパッケージ。
PyCall パッケージを利用して、Python の matplotlib.animation を利用する。
Distributions は確率分布のパッケージ。
自由度 df のカイ二乗分布は Chisq(df)
である。
確率分布 d に従って乱数を N 個発生させるには rand(d,N)
を使う。
確率密度函数は pdf(d,N)
と書く。
showgif(filename)
はGIFファイルを表示するための函数。
plotchisqsim(df)
は自由度 df のカイ二乗分布で乱数を N=10^4 個生成して、確率密度函数と比較するグラフを描く函数である。ただし、anim.FuncAnimation 函数で使用するために、最終行は plot()
でなければいけない。
clf()
は図のクリア。
plt[:hist]
でヒストグラムを描く。 normed=true
で確率密度函数と比較可能なヒストグラムになる。
frames = [1;1;1:30;29:-1:2]
は 1,1,1,2,3,...,30,29,28,...,3,2 という数列になる。自由度をその数列の範囲内で動かす。
anim.FuncAnimation(fig, plotchisqsim, frames=frames, interval=100)
の意味は以下の通り。
fig
で図を描く。
plotchisqsim(x)
でアニメーションの1コマ分をプロットする。
frames=frames
にしたがって x を動かす。
interval=100
は1コマあたり100msという意味。
matplotlib[:__version__]
"2.2.2"