Adding Plotly Traces to an Array

I am attempting to plot multiple traces using the PlotlyJS backend and there are too many to do manually. My idea is to do something of the sort:

for idx in 1:size(data)[2]
    traces[idx] = scatter(x=r_range,
                         y=data[:,idx],
                        mode="lines",
                        name = "$idx")
end

However, I need to allocate the traces array to be able to use it. I tried doing traces = Array{Any,1}() and using push! to populate it, which worked, but when I plot, I get the following error:

ERROR: LoadError: MethodError: no method matching Plot(::Vector{Any}, ::Layout{Dict{Symbol, Any}})
Closest candidates are:
  Plot(::AbstractArray{T}, ::Layout; kwargs...) where T<:Union{Dates.Date, Dates.DateTime, AbstractString, Number, Symbol} at C:\Users\Paul\.julia\packages\PlotlyBase\xb3Du\src\convenience_api.jl:78
  Plot(::TT, ::TL, ::TF, ::Base.UUID, ::PlotConfig) where {TT<:(AbstractVector{<:AbstractTrace}), TL<:AbstractLayout, TF<:(AbstractVector{<:PlotlyFrame})} at C:\Users\Paul\.julia\packages\PlotlyBase\xb3Du\src\PlotlyBase.jl:79
  Plot(::AbstractVector{<:AbstractTrace}, ::Any) at C:\Users\Paul\.julia\packages\PlotlyBase\xb3Du\src\PlotlyBase.jl:105

I tried playing around with AbstractArrays to no avail.

Here’s an overview of my code:

using PlotlyJS

# Measurement Generation
data = rand(Float64, (100, 5))
r_range = 10:10:90


for idx in 1:size(data)[2]
    push!(traces, scatter(x=r_range,
                         y=data[:,idx],
                        mode="lines",
                        name = "$idx")
end

plot_size = 800

layout = Layout(
    xaxis_label = "x",
    yaxis_label = "y",
    font = attr(size=16),
    width=plot_size, height=plot_size,
    template = "plotly_white"
)

analysis_plot = plot(traces, layout)

My goal would be to automate the process via a for loop and get a similar result as THIS tutorial.
I would appreciate any insight as to the best way to allocate the array which works with Plotly. Thanks

Why not using the builtin function: add_trace!()

You can pre-allocate a vector of traces:

nr_of_traces = size(data, 2)
traces = Vector{GenericTrace}(undef, nr_of_traces)
for idx in 1:nr_of_traces
    traces[idx] = scatter(x=r_range,  y=data[:,idx],
                        mode="lines",
                        name = "$idx")
end

If you don’t know in advance how many traces will be needed, start with

traces = GenericTrace[]

then push!(traces, scatter(...))

2 Likes