Skip to content

Instantly share code, notes, and snippets.

@asinghvi17
Last active May 7, 2022 14:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save asinghvi17/5d062158cb72d5c941e1ec664d574d4d to your computer and use it in GitHub Desktop.
Save asinghvi17/5d062158cb72d5c941e1ec664d574d4d to your computer and use it in GitHub Desktop.
Interactive cobweb plot with Makie
using Makie, GLMakie
f(x::Real, r::Real) = r * x * (1 - x)
function cobweb(
xᵢ::Real,
curve_f::Function,
r::Real;
nstep::Real = 30
)::Vector{Point2f} # col 1 is x, col 2 is y
a = zeros(nstep*2, 2)
a[1, 1] = xᵢ
x = xᵢ
y = curve_f(x, r)
ret = similar(Vector{Point2f}, nstep*2)
ret[1] = Point2f(x, 0)
for i ∈ 2:2:nstep*2-2
a[i, 1] = x
a[i, 2] = y
x = y
y = curve_f(x, r)
a[i+1, 1] = x
a[i+1, 2] = x
ret[i] = Point2f(a[i, 1], a[i, 2])
ret[i+1] = Point2f(a[i+1, 1], a[i+1, 2])
end
return ret
end
xᵢ = 0.1
rᵢ = 2.8
xr = 0:0.001:1
fig = Figure()
ax = Axis(
fig[1, 1],
xlabel = L"x_{n}",
xlabelsize = 30,
ylabel = L"x_{n+1}",
ylabelsize = 30,
title = "Cobweb plot",
aspect = AxisAspect(1),
)
sg = SliderGrid(fig[2, 1],
(label = "xᵢ", range = 0:0.01:1, startvalue = xᵢ),
(label = "r", range = 0:0.01:4, startvalue = rᵢ),
)
fs = lift(r -> f.(xr, r), sg.sliders[2].value)
cw = lift((x, r) -> cobweb(x, f, r), sg.sliders[1].value, sg.sliders[2].value)
lines!(ax, # plot x=y, the bisector line
xr, # xs
xr, # ys
linestyle = :dash, # style of line
linewidth = 3, # width of line
color = :blue # colour of line
)
lines!(ax, xr, fs) # plot the curve
lines!(ax, cw) # plot the cobweb
# Set up mouse interaction
MakieLayout.deactivate_interaction!(ax, :rectanglezoom)
point = select_point(ax.scene)
on(point) do val
set_close_to!(sg.sliders[1], val[1])
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment