カイ二乗分布のGIFアニメーション

黒木玄

2017-09-23

In [1]:
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.491345 seconds (252.93 k allocations: 13.565 MiB)
 21.904724 seconds (776.50 k allocations: 44.449 MiB, 0.07% gc time)