How to Transform Plots / Shape with Plots.jl

Defining new types may be a bit of an overkill for this problem if it does not repeat a few times. Here is another function with some ‘functional’ approach:

function make_fg_plot()
    f(x) = sin(x^2) + cos(2x) - 6
    g(x) = sin(x^2) + cos(2x)

    yshift = y -> y + 5
    yreflection = y -> -y
    ytransform = yshift ∘ yreflection

    plt = plot(; ylims = (-8, 15), legend = :topleft)
    for (T, attrs) in [(identity, (;label = "", linecolor = :green)), 
                       (ytransform, (;label = "", linecolor = :red))]
        plot!(plt, T ∘ f, 2, 4; attrs...)
        plot!(plt, T ∘ g, 2, 4; attrs...)

        plot!(plt, [2, 2], T.([f(2), g(2)]); attrs...)
        plot!(plt, [4, 4], T.([f(4), g(4)]); attrs...)
    end
    return plt
end

This function returns the plt object and may be called from REPL or displayed otherwise.

3 Likes