How to animate a plot with subplots

I’d like to make an animation of a figure with two subplots.

using Plots

x_data = range(0.0,stop=2π, length=1000)
y_data = sin.(x_data) .+ 0.1.*randn(1000,100)

@gif for i ∈ 1:100
    fig = plot(layout = grid(2,1), legend=false)

    plot(fig[1], 
        x_data, y_data)
    vline!([x_data[i]])

    # histogram!(fig[2],y_data[i,:])
end

Gets this:

download

If I remove the comment from the histogram line, I get this:
download (1)

How can I have both subplots show in the animation?

This other thread has a very nice example of animated subplots.

1 Like

I also just realized I was missing a ! after my first plot :man_facepalming:

You think I should delete this thread since it was just a simple syntax error? I did make note of that other one you linked to, and it’s helpful for making things look really nice!

I would leave it and post the corrected code and the final animation. It will surely be useful to others.

1 Like
using Plots

x_data = range(0.0,stop=2π, length=1000)
y_data = sin.(x_data) .+ 0.1.*randn(1000,100)

@gif for i ∈ 1:100
    fig = plot(layout = grid(2,1), legend=false)

    plot!(fig[1], # ADD !
        x_data, y_data)
    vline!([x_data[i]])

    histogram!(fig[2],y_data[i,:],
    xlim=(-1.2,1.2), ylim=(0,50)) # Also added to make it less jumpy.
end

download (1)

2 Likes