QuantEcon / lecture-julia.myst

Lecture source for "Quantitative Economics with Julia"
https://julia.quantecon.org/intro.html
53 stars 43 forks source link

Update plotting in the scalar dynamics #234

Closed jlperla closed 8 months ago

jlperla commented 1 year ago

https://julia.quantecon.org/introduction_dynamics/scalar_dynam.html

Cleaned up plotting code to merge in:

# Iterates a function from an initial condition 
function iterate_map(f, x0, T)
    x = zeros(T+1)
    x[1] = x0
    for t in 2:(T+1)
        x[t] = f(x[t-1])
    end
    return x
end

function plot45(f, xmin, xmax, x0, T; num_points = 100, label = L"g(k)", xlabel = "k")
    # Plot the function and the 45 degree line
    x_grid = range(xmin, xmax, num_points)
    plt = plot(x_grid, f.(x_grid); xlim=(xmin, xmax), ylim=(xmin, xmax), linecolor=:black, lw=2, label)
    plot!(x_grid, x_grid; linecolor=:blue, lw=2, label = nothing)

    # Iterate map and add ticks
    x = iterate_map(f, x0, T)
    xticks!(x, [L"%$(xlabel)_{%$i}" for i in 0:T])
    yticks!(x, [L"%$(xlabel)_{%$i}" for i in 0:T])    

    # Plot arrows and dashes
    for i in 1:T
        plot!([x[i], x[i]], [x[i], x[i+1]], arrow=:closed, linecolor=:black, alpha=0.5, label = nothing)
        plot!([x[i], x[i+1]], [x[i+1], x[i+1]], arrow=:closed, linecolor=:black, alpha=0.5, label = nothing)
        plot!([x[i+1], x[i+1]], [0, x[i+1]], linestyle=:dash, linecolor=:black, alpha=0.5, label = nothing)
    end
    plot!([x[1], x[1]], [0, x[1]], linestyle=:dash, linecolor=:black, alpha=0.5, label = nothing)
end  

function ts_plot(f, x0, T; xlabel=L"t", label=L"k_t")
    x = iterate_map(f, x0, T)
    plot(0:T, x; xlabel, label)
    plot!(0:T, x; seriestype=:scatter, mc=:blue, alpha=0.7, label=nothing)
end
jlperla commented 1 year ago

@Jonah-Heyl This one is a little more substantial. Here I have copied the rewritten code that I used in the problem sets, which we should implement in that lecture.

You can look at our class problem sets to see if you want to refactor/rewrite the code in scalar dynamics that uses this code to make things clearer as well. Good time for a general cleanup.