In [1]:
using Reactive, Interact
Interactive plotting can be useful and fun. Here we have a few examples to get you started creating your own interactive plots. We will extensively use the @manipulate
macro from the introductory notebook.
Compose is an excellent tool for creating declarative vector graphics. Here is an example compose diagram you can play around with.
In [2]:
using Colors
using Compose
@manipulate for color=["yellow", "cyan", "tomato"], rotate=0:.05:2π, n=3:20
compose(context(), fill(parse(Colorant, color)),
polygon([((1+sin(θ+rotate))/2, (1+cos(θ+rotate))/2) for θ in 0:2π/n:2π]))
end
Out[2]:
In [3]:
using Gadfly
In [4]:
@manipulate for ϕ = 0:π/16:4π, f = [sin, cos], both = false
if both
plot([θ -> sin(θ + ϕ), θ -> cos(θ + ϕ)], 0, 8)
else
plot(θ -> f(θ + ϕ), 0, 8)
end
end
Out[4]:
In [5]:
@manipulate for n=1:25, g=[Geom.point, Geom.line]
Gadfly.plot(y=rand(n), x=rand(n), g)
end
Out[5]:
In [6]:
using PyPlot
Since PyPlot images are often displayed as the result of function side-effects, you'll need to take an extra step in order for interactive PyPlot graphics to be updated properly as widget values are updated. You do this by using the withfig
function to specify a figure object that will be updated in each iteration of @manipulate
. Notice f = figure()
and withfig(f)
in the example below. The rest of it is straightforward.
In [7]:
f = figure()
x = linspace(0,2π,1000)
@manipulate for α=1:0.1:3, β=1:0.1:3, γ=1:0.1:3, leg="a funny plot"; withfig(f) do
PyPlot.plot(x, cos(α*x + sin(β*x + γ)))
legend([leg])
end
end
Out[7]:
As an added bonus, you can even fire up a Python GUI with pygui(true)
and be able to use the widgets above to update the plot.
Manipulating a PyPlot figure with multiple subplots adds an extra layer of complication. The withfig
function clears the current figure window by default at each @manipulate
iteration. If you're manipulating multiple subplots in one figure they will not be displayed correctly. To prevent subplots being destroyed use withfig(f,clear=false)
. Setting clear=false
leaves the responsibility for clearing the figure window up to the user. In the case of multiple subplots you can clear each axes object individually, rather than the figure itself. This is shown in the example below.
In [8]:
f2,axes = subplots(2,1)
x = linspace(0,2π,1000)
@manipulate for α=1:0.1:3, β=1:0.1:3, γ=1:0.1:3, leg1="a funny plot", leg2=" an even funnier plot"
withfig(f2,clear=false) do
for ax in axes
ax[:cla]()
end
axes[1][:plot](x, sin(α*x + cos(β*x + γ)))
axes[2][:plot](x, cos(α*x + sin(β*x + γ)))
axes[1][:legend]([leg1])
axes[2][:legend]([leg2])
end
end
Out[8]:
In [ ]: