黒木玄
2018-01-29, 2018-09-13, 2018-12-13
PyPlot.jl によるプロットと Plots.jl によるプロットを比較してみる.
import PyPlot
を using PyPlot
に変えれば PyPlot.
を省略できる. これは Plots
についても同様である. しかし, using PyPlot
と using Plots
は両立しないので注意せよ.
警告: 筆者は特に Plots.jl の経験が浅く, よく理解していない部分が多数ある.
using Base64
using Pkg
using Random
endof(a) = lastindex(a)
linspace(start, stop, length) = range(start, stop=stop, length=length)
const srand = Random.seed!
displayfile(mime, file) = open(file) do f
base64 = base64encode(f)
display("text/html", """<img src="data:$mime;base64,$base64">""")
end
using Distributions
import PyPlot
import Plotly
import Plots
import PyPlot
PyPlot.plt[:style][:use]("default")
PyPlot.rc("figure", titlesize=10)
PyPlot.rc("lines", linewidth=1)
PyPlot.rc("lines", markersize=5)
PyPlot.rc("axes", grid=true)
PyPlot.rc("axes", labelsize=10)
PyPlot.rc("grid", linestyle=":")
PyPlot.rc("xtick", labelsize=8)
PyPlot.rc("ytick", labelsize=8)
PyPlot.rc("legend", fontsize=8)
srand(12345)
N = 20
PyPlot.figure(figsize=(5,5))
PyPlot.plot(rand(N), rand(N), label="1", marker="o")
PyPlot.plot(rand(N), rand(N), label="2", marker="^", ls="--")
PyPlot.plot(rand(N), rand(N), label="3", marker="s", ls="-.")
PyPlot.legend()
PyPlot.xlim(-0.05, 1.05)
PyPlot.ylim(-0.05, 1.05)
PyPlot.xlabel("x")
PyPlot.ylabel("y")
PyPlot.axes()[:set_aspect]("equal")
PyPlot.title("2-dimensional uniform distribution")
PyObject Text(0.5,1,'2-dimensional uniform distribution')
import Plots
Plots.reset_defaults()
Plots.pyplot(
legend=false,
titlefont=Plots.font("sans-serif", 12),
legendfont=Plots.font("sans-serif", 8),
guidefont=Plots.font("sans-serif", 10),
tickfont=Plots.font("sans-serif", 8),
markersize=5,
markerstrokewidth=0,
)
srand(12345)
N = 20
Plots.plot(size=(450, 450))
Plots.plot!(rand(N), rand(N), label="1", marker=:circle)
Plots.plot!(rand(N), rand(N), label="2", marker=:utriangle, ls=:dash)
Plots.plot!(rand(N), rand(N), label="3", marker=:square, ls=:dashdot)
Plots.plot!(legend=true)
Plots.plot!(xlim=(-0.05, 1.05))
Plots.plot!(ylim=(-0.05, 1.05))
Plots.plot!(xlabel="x")
Plots.plot!(ylabel="y")
Plots.plot!(aspect_ratio=1)
Plots.title!("2-dimensional uniform distribution")
import Plots
Plots.reset_defaults()
Plots.gr(
legend=false,
titlefont=Plots.font("sans-serif", 12),
legendfont=Plots.font("sans-serif", 8),
guidefont=Plots.font("sans-serif", 10),
tickfont=Plots.font("sans-serif", 8),
markersize=5,
markerstrokewidth=0,
)
srand(12345)
N = 20
Plots.plot(size=(450, 450))
Plots.plot!(rand(N), rand(N), label="1", marker=:circle)
Plots.plot!(rand(N), rand(N), label="2", marker=:utriangle, ls=:dash)
Plots.plot!(rand(N), rand(N), label="3", marker=:square, ls=:dashdot)
Plots.plot!(legend=true)
Plots.plot!(xlim=(-0.05, 1.05))
Plots.plot!(ylim=(-0.05, 1.05))
Plots.plot!(xlabel="x")
Plots.plot!(ylabel="y")
Plots.plot!(aspect_ratio=1)
Plots.title!("2-dimensional uniform distribution")
import Plots
Plots.reset_defaults()
#Plots.plotlyjs(
Plots.plotly(
legend=false,
titlefont=Plots.font("sans-serif", 12),
legendfont=Plots.font("sans-serif", 8),
guidefont=Plots.font("sans-serif", 10),
tickfont=Plots.font("sans-serif", 8),
markersize=5,
markerstrokewidth=0,
)
srand(12345)
N = 20
Plots.plot(size=(500,420))
Plots.plot!(rand(N), rand(N), label="1", marker=:circle)
Plots.plot!(rand(N), rand(N), label="2", marker=:utriangle, ls=:dash)
Plots.plot!(rand(N), rand(N), label="3", marker=:square, ls=:dashdot)
Plots.plot!(legend=true)
Plots.plot!(xlim=(-0.05, 1.05))
Plots.plot!(ylim=(-0.05, 1.05))
Plots.plot!(xlabel="x")
Plots.plot!(ylabel="y")
Plots.plot!(aspect_ratio=0.85)
Plots.title!("2-dimensional uniform distribution")
using KernelDensity
srand(2018)
X = vcat(2 .+ 2*randn(6000), -3 .+ 0.5*randn(4000))
ik = InterpKDE(kde(X))
pdfik(x) = pdf(ik, x)
x = linspace(minimum(X), maximum(X), 401)
y = pdfik.(x)
import PyPlot
PyPlot.plt[:style][:use]("default")
PyPlot.rc("figure", titlesize=10)
PyPlot.rc("lines", linewidth=1)
PyPlot.rc("axes", grid=true)
PyPlot.rc("axes", labelsize=10)
PyPlot.rc("grid", linestyle=":")
PyPlot.rc("xtick", labelsize=8)
PyPlot.rc("ytick", labelsize=8)
PyPlot.rc("legend", fontsize=10)
PyPlot.figure(figsize=(5, 3.5))
PyPlot.plt[:hist](X, normed=true, bins=100, alpha=0.3, label="sample")
PyPlot.plot(x, y, label="kde")
PyPlot.legend()
PyPlot.xlabel("x")
PyPlot.ylabel("probability density")
PyPlot.title("sample of mixture normal distribution")
PyObject Text(0.5,1,'sample of mixture normal distribution')
using KernelDensity
srand(2018)
X = vcat(2 .+ 2*randn(6000), -3 .+ 0.5*randn(4000))
ik = InterpKDE(kde(X))
pdfik(x) = pdf(ik, x)
x = linspace(minimum(X), maximum(X), 401)
y = pdfik.(x)
import Plots
Plots.reset_defaults()
Plots.pyplot(
legend=false,
titlefont=Plots.font("sans-serif", 12),
legendfont=Plots.font("sans-serif", 10),
guidefont=Plots.font("sans-serif", 10),
tickfont=Plots.font("sans-serif", 8),
)
Plots.plot(size=(450, 315))
Plots.histogram!(X, normed=true, bins=100, alpha=0.2, label="sample", legend=true)
Plots.plot!(x, y, label="kde", legend=true, ylims=(0, 0.33))
Plots.plot!(xlabel="x")
Plots.plot!(ylabel="probability density")
Plots.title!("sample of mixture normal distribution")
using KernelDensity
srand(2018)
X = vcat(2 .+ 2*randn(6000), -3 .+ 0.5*randn(4000))
ik = InterpKDE(kde(X))
pdfik(x) = pdf(ik, x)
x = linspace(minimum(X), maximum(X), 401)
y = pdfik.(x)
import Plots
Plots.reset_defaults()
Plots.gr(
legend=false,
titlefont=Plots.font("sans-serif", 12),
legendfont=Plots.font("sans-serif", 10),
guidefont=Plots.font("sans-serif", 10),
tickfont=Plots.font("sans-serif", 8),
)
Plots.plot(size=(450, 315))
Plots.histogram!(X, normed=true, bins=100, alpha=0.2, label="sample", legend=true)
Plots.plot!(x, y, label="kde", legend=true, ylims=(0, 0.33))
Plots.plot!(xlabel="x")
Plots.plot!(ylabel="probability density")
Plots.title!("sample of mixture normal distribution")
using KernelDensity
srand(2018)
n = 2^10
X, Y = randn(n), randn(n)
X, Y = 2X, X.^2 + X + 1.2Y
ik = InterpKDE(kde((X,Y)))
pdfik(x,y) = pdf(ik,x,y)
c = pdfik.(X, Y)
x = linspace(minimum(X), maximum(X), 201)
y = linspace(minimum(Y), maximum(Y), 201)
z = pdfik.(x', y)
import PyPlot
PyPlot.plt[:style][:use]("default")
PyPlot.rc("lines", markersize=2)
PyPlot.rc("grid", linestyle=":")
PyPlot.rc("axes", facecolor="gray")
PyPlot.figure(figsize=(8,3.4))
PyPlot.subplot(121)
PyPlot.scatter(X, Y, c=c, cmap="CMRmap")
PyPlot.colorbar()
PyPlot.title("scatter")
PyPlot.subplot(122)
PyPlot.pcolormesh(x, y, z, cmap="CMRmap")
PyPlot.colorbar()
PyPlot.title("pcolormesh")
PyPlot.tight_layout()
PyPlot.savefig("PyPlot_scatter_pcolormesh.png")
displayfile("image/png", "PyPlot_scatter_pcolormesh.png")
using KernelDensity
srand(2018)
n = 2^10
X, Y = randn(n), randn(n)
X, Y = 2X, X.^2 + X + 1.2Y
ik = InterpKDE(kde((X,Y)))
pdfik(x,y) = pdf(ik,x,y)
c = pdfik.(X, Y)
x = linspace(minimum(X), maximum(X), 201)
y = linspace(minimum(Y), maximum(Y), 201)
z = pdfik.(x', y)
import Plots
Plots.reset_defaults()
Plots.pyplot(
legend=false,
markersize=3,
markerstrokewidth=0,
background_color_inside="gray",
)
p1 = Plots.scatter(X, Y, zcolor=c, color=:thermal, colorbar=true, title="scatter")
p2 = Plots.heatmap(x, y, z, color=:thermal, colorbar=true, title="heatmap")
Plots.plot(p1, p2, size=(720, 320))
Plots.savefig("Plots_pyplot_scatter_heatmap.png")
displayfile("image/png", "Plots_pyplot_scatter_heatmap.png")
using KernelDensity
srand(2018)
n = 2^10
X, Y = randn(n), randn(n)
X, Y = 2X, X.^2 + X + 1.2Y
ik = InterpKDE(kde((X,Y)))
pdfik(x,y) = pdf(ik,x,y)
c = pdfik.(X, Y)
x = linspace(minimum(X), maximum(X), 201)
y = linspace(minimum(Y), maximum(Y), 201)
z = pdfik.(x', y)
import Plots
Plots.reset_defaults()
Plots.gr(
legend=false,
markersize=3,
markerstrokewidth=0,
background_color_inside="gray",
)
p1 = Plots.scatter(X, Y, zcolor=c, color=:thermal, colorbar=true, title="scatter")
p2 = Plots.heatmap(x, y, z, color=:thermal, colorbar=true, title="heatmap")
Plots.plot(p1, p2, size=(800, 320))
Plots.savefig("Plots_gr_scatter_heatmap.png")
Plots.plot(p1, p2, size=(800, 320))
displayfile("image/png", "Plots_gr_scatter_heatmap.png")
R = 10
r = 3
f(u,v) = R*cos(u) + cos(u)*r*cos(v)
g(u,v) = R*sin(u) + sin(u)*r*cos(v)
h(u,v) = r*sin(v)
u = linspace(0, 2π, 21)
v = linspace(0, 2π, 21)
x = f.(u',v)
y = g.(u',v)
z = h.(u',v)
t = 0.2π
y, z = cos(t)*y-sin(t)*z, sin(t)*y + cos(t)*z
import PyPlot
PyPlot.plt[:style][:use]("default")
PyPlot.rc("figure", titlesize=10)
PyPlot.rc("axes", labelsize=10)
PyPlot.rc("xtick", labelsize=8)
PyPlot.rc("ytick", labelsize=8)
PyPlot.rc("legend", fontsize=8)
PyPlot.rc("grid", linestyle=":")
PyPlot.figure(figsize=(6, 4))
s = PyPlot.plot_surface(x, y, z, cmap="rainbow")
PyPlot.colorbar(s)
PyPlot.zlim(-10,10)
PyPlot.tick_params(axis="x", rotation=15)
PyPlot.tick_params(axis="y", rotation=-15)
PyPlot.tick_params(axis="z", rotation=-10)
PyPlot.xlabel("x")
PyPlot.ylabel("y")
PyPlot.title("torus")
PyPlot.figure(figsize=(5, 4))
PyPlot.plot_wireframe(x, y, z, cmap="rainbow")
PyPlot.zlim(-10,10)
PyPlot.tick_params(axis="x", rotation=15)
PyPlot.tick_params(axis="y", rotation=-15)
PyPlot.tick_params(axis="z", rotation=-10)
PyPlot.xlabel("x")
PyPlot.ylabel("y")
PyPlot.title("torus")
PyObject Text(0.5,0.92,'torus')
R = 10
r = 3
f(u,v) = R*cos(u) + cos(u)*r*cos(v)
g(u,v) = R*sin(u) + sin(u)*r*cos(v)
h(u,v) = r*sin(v)
u = linspace(0, 2π, 21)
v = linspace(0, 2π, 21)
x = f.(u',v)
y = g.(u',v)
z = h.(u',v)
t = 0.2π
y, z = cos(t)*y-sin(t)*z, sin(t)*y + cos(t)*z
import PyPlot
PyPlot.plt[:style][:use]("default")
PyPlot.rc("figure", titlesize=10)
PyPlot.rc("axes", labelsize=10)
PyPlot.rc("xtick", labelsize=8)
PyPlot.rc("ytick", labelsize=8)
PyPlot.rc("legend", fontsize=8)
PyPlot.rc("grid", linestyle=":")
PyPlot.figure(figsize=(10, 4))
ax1 = PyPlot.subplot2grid((1,11), (0,0), rowspan=1, colspan=6, projection="3d")
ax1[:view_init](30, -120)
s1 = PyPlot.plot_surface(x, y, z, cmap="rainbow")
PyPlot.colorbar(s1)
PyPlot.zlim(-10,10)
PyPlot.tick_params(axis="x", rotation=15)
PyPlot.tick_params(axis="y", rotation=-15)
PyPlot.tick_params(axis="z", rotation=-10)
PyPlot.xlabel("x")
PyPlot.ylabel("y")
PyPlot.title("torus")
PyPlot.subplot2grid((1,11), (0,6), rowspan=1, colspan=5, projection="3d")
PyPlot.plot_wireframe(x, y, z, cmap="rainbow")
PyPlot.zlim(-10,10)
PyPlot.tick_params(axis="x", rotation=15)
PyPlot.tick_params(axis="y", rotation=-15)
PyPlot.tick_params(axis="z", rotation=-10)
PyPlot.xlabel("x")
PyPlot.ylabel("y")
PyPlot.title("torus")
PyPlot.tight_layout()
PyPlot.savefig("PyPlot_3D.png")
R = 10
r = 3
f(u,v) = R*cos(u) + cos(u)*r*cos(v)
g(u,v) = R*sin(u) + sin(u)*r*cos(v)
h(u,v) = r*sin(v)
u = linspace(0, 2π, 21)
v = linspace(0, 2π, 21)
x = f.(u',v)
y = g.(u',v)
z = h.(u',v)
t = 0.2π
y, z = cos(t)*y-sin(t)*z, sin(t)*y + cos(t)*z
import Plots
Plots.reset_defaults()
Plots.pyplot(
legend=false,
titlefont=Plots.font("sans-serif", 12),
legendfont=Plots.font("sans-serif", 8),
guidefont=Plots.font("sans-serif", 10),
tickfont=Plots.font("sans-serif", 8),
markersize=5,
markerstrokewidth=0,
)
#Plots.clibrary(:misc)
Plots.clibrary(:colorcet)
p1 = Plots.surface(x, y, z, color=:rainbow, colorbar=true, camera=(-30, 30))
Plots.plot!(p1, zlim=(-10,10))
Plots.plot!(p1, xlabel="x")
Plots.plot!(p1, ylabel="y")
Plots.title!(p1, "torus")
p2 = Plots.wireframe(x, y, z)
Plots.plot!(p2, zlim=(-10,10))
Plots.plot!(p2, xlabel="x")
Plots.plot!(p2, ylabel="y")
Plots.title!(p2, "torus")
#Plots.plot(p1, p2, size=(900, 360))
Plots.plot(p1, size=(450, 360))
Plots.savefig("Plots_pyplot_3D.png")
R = 10
r = 3
f(u,v) = R*cos(u) + cos(u)*r*cos(v)
g(u,v) = R*sin(u) + sin(u)*r*cos(v)
h(u,v) = r*sin(v)
u = linspace(0, 2π, 21)
v = linspace(0, 2π, 21)
x = f.(u',v)
y = g.(u',v)
z = h.(u',v)
t = 0.2π
y, z = cos(t)*y-sin(t)*z, sin(t)*y + cos(t)*z
import Plots
Plots.reset_defaults()
#Plots.plotlyjs(
Plots.plotly(
legend=false,
titlefont=Plots.font("sans-serif", 12),
legendfont=Plots.font("sans-serif", 8),
guidefont=Plots.font("sans-serif", 10),
tickfont=Plots.font("sans-serif", 8),
markersize=5,
markerstrokewidth=0,
)
#Plots.clibrary(:misc)
Plots.clibrary(:colorcet)
Plots.plot(size=(500, 400))
Plots.surface!(x, y, z, color=:rainbow)#, colorbar=true)
Plots.plot!(zlim=(-10,10))
Plots.plot!(xlabel="x")
Plots.plot!(ylabel="y")
Plots.title!("torus")
上のセルの出力は Jupyter notebook viewer では表示されない。
using Distributions
function asset_update!(asset, taxfunc, niters)
n = endof(asset)
ur = UnitRange{Int32}(1:n)
for iter in 1:niters
k = rand(ur)
l = rand(ur)
d = taxfunc(asset[k])
asset[k] -= d
asset[l] += d
end
end
function sim!(asset, taxfunc; niters=5*10^5, nframes=100, thin=niters÷nframes)
n = endof(asset)
T = eltype(asset)
niters = thin * nframes
Asset = zeros(T, n, nframes+1) #Array{T, 2}(undef, n, nframes+1)
Asset[:,1] .= asset
for t in 1:nframes
asset_update!(asset, taxfunc, thin)
Asset[:,t+1] .= asset
end
Asset
end
function Elog(Asset)
n, L = size(Asset)
ElogA = Array{eltype(Asset),1}(undef, L)
for l in 1:L
ElogA[l] = mean(log(Asset[k,l]) for k in 1:n)
end
ElogA
end
mutable struct ConstantRateTax{T<:AbstractFloat}; rate::T; end
ConstantRateTax(; rate = 0.2) = ConstantRateTax(rate)
(f::ConstantRateTax)(x) = f.rate * x
srand(2018)
n = 2^16
asset = rand(Exponential(1.0), n)
taxfunc = ConstantRateTax(rate=0.05)
@time Asset = sim!(asset, taxfunc, niters=4*10^6, nframes=40);
0.346461 seconds (486.05 k allocations: 43.858 MiB, 7.68% gc time)
import PyPlot
PyPlot.rc("figure", titlesize=10)
PyPlot.rc("lines", linewidth=1)
PyPlot.rc("lines", markersize=5)
PyPlot.rc("axes", grid=true)
PyPlot.rc("axes", labelsize=10)
PyPlot.rc("grid", linestyle=":")
PyPlot.rc("xtick", labelsize=8)
PyPlot.rc("ytick", labelsize=8)
PyPlot.rc("legend", fontsize=8)
using PyCall
anim = pyimport("matplotlib.animation")
using Distributions
function PyPlot_plot_Asset(t, Asset, ElogA; xmax=4.0, ymax=2.0)
n, L = size(Asset)
bins = max(41, Int(fld(sqrt(n), 2)))
PyPlot.clf()
PyPlot.subplot(121)
PyPlot.plt[:hist](@view(Asset[:,t+1]), normed=true, bins=bins, alpha=0.5, range=(0,xmax), label="asset dist")
fitdist = fit(Gamma, @view(Asset[:,t+1]))
x = linspace(0, xmax, 201)
PyPlot.plot(x, pdf.(fitdist, x), label="Gamma dist")
PyPlot.ylim(0,ymax)
PyPlot.legend()
PyPlot.title("t = $t")
PyPlot.subplot(122)
PyPlot.plot(0:t, ElogA[1:t+1])
PyPlot.xlim(0, L-1)
PyPlot.ylim(minimum(ElogA), 0)
PyPlot.title("mean of log(asset)")
PyPlot.tight_layout()
PyPlot.plot()
end
function PyPlot_makegif(giffile, Asset)
L = size(Asset)[2]-1
ElogA = Elog(Asset)
# t = 0~L について1フレーム分の画像を作成
update(t) = PyPlot_plot_Asset(t, Asset, ElogA)
# アニメーション作成開始
fig = PyPlot.figure(figsize=(7, 2.5))
# t の動かし方
frames = [0;0;0;0;0;0;0;0;0:L;L;L;L;L;L;L;L;L;L:-1:0]
# アニメ―ションオブジェクトの作成
myanim = anim[:FuncAnimation](fig, update, frames=frames, interval=100)
# GIFファイルの作成
myanim[:save](giffile, writer="imagemagick")
# 無駄な表示を削除
PyPlot.clf()
end
giffile = "PyPlot_asset_dist.gif"
@time PyPlot_makegif(giffile, Asset)
displayfile("image/gif", giffile)
51.983871 seconds (3.35 M allocations: 164.674 MiB, 0.41% gc time)
こちらの方がGIFアニメ作成よりも速い.
import PyPlot
PyPlot.rc("figure", titlesize=10)
PyPlot.rc("lines", linewidth=1)
PyPlot.rc("lines", markersize=5)
PyPlot.rc("axes", grid=true)
PyPlot.rc("axes", labelsize=10)
PyPlot.rc("grid", linestyle=":")
PyPlot.rc("xtick", labelsize=8)
PyPlot.rc("ytick", labelsize=8)
PyPlot.rc("legend", fontsize=8)
using PyCall
anim = pyimport("matplotlib.animation")
using Distributions
function PyPlot_plot_Asset(t, Asset, ElogA; xmax=4.0, ymax=2.0)
n, L = size(Asset)
bins = max(41, Int(fld(sqrt(n), 2)))
PyPlot.clf()
PyPlot.subplot(121)
PyPlot.plt[:hist](@view(Asset[:,t+1]), normed=true, bins=bins, alpha=0.5, range=(0,xmax), label="asset dist")
fitdist = fit(Gamma, @view(Asset[:,t+1]))
x = linspace(0, xmax, 201)
PyPlot.plot(x, pdf.(fitdist, x), label="Gamma dist")
PyPlot.ylim(0,ymax)
PyPlot.legend()
PyPlot.title("t = $t")
PyPlot.subplot(122)
PyPlot.plot(0:t, ElogA[1:t+1])
PyPlot.xlim(0, L-1)
PyPlot.ylim(minimum(ElogA), 0)
PyPlot.title("mean of log(asset)")
PyPlot.tight_layout()
PyPlot.plot()
end
function PyPlot_makehtml(Asset)
L = size(Asset)[2]-1
ElogA = Elog(Asset)
# t = 0~L について1フレーム分の画像を作成
update(t) = PyPlot_plot_Asset(t, Asset, ElogA)
# アニメーション作成開始
fig = PyPlot.figure(figsize=(7, 2.5))
# t の動かし方
frames = [0;0;0;0;0;0;0;0;0:L;L;L;L;L;L;L;L;L;L:-1:0]
# アニメ―ションオブジェクトの作成
myanim = anim[:FuncAnimation](fig, update, frames=frames, interval=100)
# Javascript animation の作成
myanim_html = myanim[:to_jshtml]()
# 無駄な表示を削除
PyPlot.clf()
return myanim_html
end
@time myanim_html = PyPlot_makehtml(Asset)
display("text/html", myanim_html)
41.281116 seconds (543.19 k allocations: 28.256 MiB, 0.02% gc time)
非常に遅い. matplotlib.animation よりも3倍以上も時間がかかってしまう.
遅くて実用的でないと思われるのでコメントアウトしてある.
# import Plots
# Plots.reset_defaults()
# Plots.pyplot(
# legend=false,
# titlefont=Plots.font("sans-serif", 12),
# legendfont=Plots.font("sans-serif", 8),
# guidefont=Plots.font("sans-serif", 10),
# tickfont=Plots.font("sans-serif", 8),
# markerstrokewidth=0,
# )
# function Plots_plot_Asset(t, Asset, ElogA; xmax = 4.0, ymax = 2.0)
# n, L = size(Asset)
# fitdist = fit(Gamma, @view(Asset[:,t+1]))
# x = linspace(0, xmax, 201)
# p1 = Plots.histogram(@view(Asset[:,t+1]), normed=true, alpha=0.5, linealpha=0, label="asset dist")
# Plots.plot!(p1, xlim=(0,xmax), ylim=(0,ymax))
# Plots.plot!(p1, x, pdf.(fitdist, x), label="Gamma dist", legend=true)
# Plots.title!(p1, "t = $t")
# p2 = Plots.plot(0:t, ElogA[1:t+1])
# Plots.plot!(p2, [L], [0], xlim=(0,L-1))
# Plots.title!(p2, "mean of log(asset)")
# Plots.plot(p1, p2, size=(700,250))
# end
# function Plots_makegif(giffile, Asset)
# N = size(Asset)[2]-1
# ElogA = Elog(Asset)
# # t = 0~L について1フレーム分の画像を作成
# update(t) = Plots_plot_Asset(t, Asset, ElogA)
# # t の動かす範囲の指定
# frames = [0;0;0;0;0;0;0;0;0:N;N;N;N;N;N;N;N;N;N:-1:0]
# # アニメーションオブジェクトの作成
# myanim = Plots.Animation()
# # アニメーションのすべてのフレームを作成
# for t in frames
# update(t)
# Plots.frame(myanim)
# end
# # GIFファイルの作成
# Plots.gif(myanim, giffile, fps=10)
# end
# giffile = "Plots_pyplot_asset_dist.gif"
# #@time Plots_makegif(giffile, Asset[:,1:8:41]) # for test
# @time Plots_makegif(giffile, Asset)
# displayfile("image/gif", giffile)
非常に速い.
ただし 2018-01-31 現在 Plots.gr() でPNGファイルを(したがってGIFファイルを)生成するとサイズが6倍になってしまう.
さらに http://nbviewer.jupyter.org/github/goropikari/JuliaPlotsGallery.jl/blob/master/PlotsGallery.ipynb の
# Pkg.pin("Plots", v"0.14.2")
# Pkg.free("Plots")
の2行に注目.
# この環境変数が設定されていると dpi_factor = 1 となる.
ENV["PLOTS_TEST"] = "true"
"true"
###### バージョンを現在バージョンの 0.15.0 の一つ前に戻す.
###### 生成される画像ファイルのサイズが6倍になる問題対策.
###### これを実行したら, juliaを立ち上げ直す. (Kernel Restart する.)
#
#Pkg.pin("Plots", v"0.14.2")
###### もとに戻すには次を実行する
#
#Pkg.free("Plots")
###### Plots.jl のバージョンの表示
#
#Pkg.status("Plots")
以下のように
にある gr_display 函数を上書きしても6倍サイズ問題を解決できる。
# import Plots: gr_display, Plot, DPI, gr_plot_size, gr_fill_viewport, px, pt, _gr_point_mult
# function gr_display(plt::Plot, fmt="")
# GR.clearws()
# # collect some monitor/display sizes in meters and pixels
# display_width_meters, display_height_meters, display_width_px, display_height_px = GR.inqdspsize()
# display_width_ratio = display_width_meters / display_width_px
# display_height_ratio = display_height_meters / display_height_px
# # compute the viewport_canvas, normalized to the larger dimension
# viewport_canvas = Float64[0,1,0,1]
# w, h = plt[:size]
# if !haskey(ENV, "PLOTS_TEST")
# dpi_factor = plt[:dpi] / DPI
# # if fmt == "png"
# # dpi_factor *= 6
# # end
# else
# dpi_factor = 1
# end
# gr_plot_size[:] = [w, h]
# if w > h
# ratio = float(h) / w
# msize = display_width_ratio * w * dpi_factor
# GR.setwsviewport(0, msize, 0, msize * ratio)
# GR.setwswindow(0, 1, 0, ratio)
# viewport_canvas[3] *= ratio
# viewport_canvas[4] *= ratio
# else
# ratio = float(w) / h
# msize = display_height_ratio * h * dpi_factor
# GR.setwsviewport(0, msize * ratio, 0, msize)
# GR.setwswindow(0, ratio, 0, 1)
# viewport_canvas[1] *= ratio
# viewport_canvas[2] *= ratio
# end
# # fill in the viewport_canvas background
# gr_fill_viewport(viewport_canvas, plt[:background_color_outside])
# # update point mult
# px_per_pt = px / pt
# _gr_point_mult[1] = 1.5 * px_per_pt / max(h,w)
# # subplots:
# for sp in plt.subplots
# gr_display(sp, w*px, h*px, viewport_canvas)
# end
# GR.updatews()
# end
# sleep(0.1)
import Plots
Plots.reset_defaults()
Plots.gr(
legend=false,
titlefont=Plots.font("sans-serif", 12),
legendfont=Plots.font("sans-serif", 8),
guidefont=Plots.font("sans-serif", 10),
tickfont=Plots.font("sans-serif", 8),
markerstrokewidth=0,
)
function Plots_plot_Asset(t, Asset, ElogA; xmax = 4.0, ymax = 2.0)
n, L = size(Asset)
fitdist = fit(Gamma, @view(Asset[:,t+1]))
x = linspace(0, xmax, 201)
p1 = Plots.histogram(@view(Asset[:,t+1]), normed=true, alpha=0.5, linealpha=0, label="asset dist")
Plots.plot!(p1, xlim=(0,xmax), ylim=(0,ymax))
Plots.plot!(p1, x, pdf.(fitdist, x), label="Gamma dist", legend=true)
Plots.title!(p1, "t = $t")
p2 = Plots.plot(0:t, ElogA[1:t+1])
Plots.plot!(p2, [L], [0], xlim=(0,L-1))
Plots.title!(p2, "mean of log(asset)")
Plots.plot(p1, p2, size=(700, 250))
end
function Plots_makegif(giffile, Asset)
N = size(Asset)[2]-1
ElogA = Elog(Asset)
# t = 0~L について1フレーム分の画像を作成
update(t) = Plots_plot_Asset(t, Asset, ElogA)
# t の動かす範囲の指定
frames = [0;0;0;0;0;0;0;0;0:N;N;N;N;N;N;N;N;N;N:-1:0]
# アニメーションオブジェクトの作成
myanim = Plots.Animation()
# アニメーションのすべてのフレームを作成
for t in frames
update(t)
Plots.frame(myanim)
end
# GIFファイルの作成
Plots.gif(myanim, giffile, fps=10)
end
giffile = "Plots_gr_asset_dist.gif"
#@time Plots_makegif(giffile, Asset[:,1:8:41]) # for test
@time Plots_makegif(giffile, Asset)
displayfile("image/gif", giffile)
10.721578 seconds (47.71 M allocations: 1.517 GiB, 4.03% gc time)
┌ Info: Saved animation to │ fn = C:\Users\genkuroki\OneDrive\Misc\Julia-1.0\Plots_gr_asset_dist.gif └ @ Plots C:\Users\genkuroki\.julia\packages\Plots\rmogG\src\animation.jl:90