PlotlyJS.jl animation

This is an example of animation with button and slider. Each frame updates some attributes of the basic trace, as well as the layout (this example is more general than that in the link you posted). Even more general would be an example with two basic traces, each one updated by the animation frames.

using PlotlyJS

N=300
X = LinRange(0, 10, N)
Y = -3 .+ 7*rand(N)

trace = scatter(x = [X[1]],  
                y = [Y[1]],
                mode="lines",
                line_width=1.5,
                line_color="RoyalBlue")

n_frames = length(X)
frames  = Vector{PlotlyFrame}(undef, n_frames)
for k in 1:n_frames
    frames[k] = frame(data=[attr(x=X[1:k], #update x and y
                                 y=Y[1:k],
                                 )],
                      layout=attr(title_text="Test frame $k"), #update title
                      name="fr$k", #frame name; it is passed to slider 
                      traces=[0] # this means that the above data update the first trace (here the unique one) 
                        ) 
end    


updatemenus = [attr(type="buttons", 
                    active=0,
                    y=1,  #(x,y) button position 
                    x=1.1,
                    buttons=[attr(label="Play",
                                  method="animate",
                                  args=[nothing,
                                        attr(frame=attr(duration=5, 
                                                        redraw=true),
                                             transition=attr(duration=0),
                                             fromcurrent=true,
                                             mode="immediate"
                                                        )])])];


sliders = [attr(active=0, 
                minorticklen=0,
                
                steps=[attr(label="f$k",
                            method="animate",
                            args=[["fr$k"], # match the frame[:name]
                                  attr(mode="immediate",
                                       transition=attr(duration=0),
                                       frame=attr(duration=5, 
                                                  redraw=true))
                                 ]) for k in 1:n_frames ]
             )];    

ym, yM = extrema(Y)
layout = Layout(title_text="Test", title_x=0.5,
    width=700, height=450,
              xaxis_range=[-0.1, 10.1], 
              yaxis_range=[ym-1, yM+1],
              updatemenus=updatemenus,
              sliders=sliders
    )
pl = Plot(trace, layout, frames)
5 Likes