How to avoid this code duplication?

Hi,

The following Makie code appends subplots to existing plots.

Working, but…

  • Code duplication
    was needed for the optional parameter in the first position
  • function output
    was needed because mutation of input parameter not possible
  • ugly construct to be able to push!
    if !(typeof(ax) <: Vector)
        ax = [ax]
    end
  • possibly re-inventing a wheel in Makie.
using GLMakie
GLMakie.activate!()

function makie_plot(x, y; legends = [], title = [], xlabel = [], ylabel = [])
    m = size(y, 2)
    if isempty(legends)
        legends = ["y$i" for i=1:m]
    end
    # standard colors from matplotlib
    colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"];
    fig = Figure()
    ax = []
    push!(ax, Axis(fig[1, 1]))
    pl = []
    for i = 1:m
        global pl = lines!(ax[1], x, y[:,i], label = legends[i], color = colors[(i-1)%10+1])
    end
    axislegend(ax)
    if !isempty(title)
        ax[1].title = title
    end
    if !isempty(xlabel)
        ax[1].xlabel = xlabel
    end
    if !isempty(ylabel)
        ax[1].ylabel = ylabel
    end
    display(fig)
    (fig, ax, pl)
end

function makie_append_plot(fap, x, y; legends = [], title = [], xlabel = [], ylabels = [])
    m = size(y, 2)
    if isempty(legends)
        legends = ["y$i" for i=1:m]
    end
    # standard colors from matplotlib
    colors = ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"];
    fig, ax, pl = fap
    if !(typeof(ax) <: Vector)
        ax = [ax]
    end
    n = length(ax) + 1
    push!(ax, Axis(fig[n, 1]))
    linkxaxes!(ax[1], ax[n])
    for i = 1:m
        lines!(ax[n], x, y[:,i], label = legends[i], color = colors[(i-1)%10+1])
    end
    axislegend(ax[n])
    if !isempty(title)
        ax[1].title = title
    end
    if !isempty(xlabel)
        ax[end].xlabel = xlabel
    end
    hidexdecorations!.(ax[1:n-1], grid=false)
    rowgap!(fig.layout,0)
    display(fig)
    fap = (fig, ax, pl)
end

n = 100; m = 3
x = 1:n
y = randn(n,m)
fap = makie_plot(x,cumsum(y[:,1]), legends = ["cumsum(toto)"])
fap = makie_append_plot(fap, x, y, legends = ["toto", "titi", "tata"])
fap = makie_append_plot(fap, x, y.^2, legends = ["toto2", "titi2", "tata2"], title = "A Title", xlabel = "Time [s]")

Solved using multiple dispatch, see makie_addsubplot.