Skip to content

Python-Event-Loop

This guide demonstrates how to create Python-controlled animations using Colight plots, the .reset method, and interactive sliders. We'll cover: 1. Setting up a basic animated plot 2. Creating interactive animations with ipywidgets

We must use the "widget" rendering modes for bidirectional python/javascript communication:

Plot.configure({"display_as": "widget"})

First, a simple sine wave plot:

x = np.linspace(0, 10, 100)
basic_plot = (
    Plot.line(list(zip(x, np.sin(x))))
    + Plot.domain([0, 10], [-1, 1])
    + Plot.height(200)
)
basic_plot

Now, let's animate it:

Plot.html(
    [
        "div.bg-black.text-white.p-3",
        """The following examples depend on communication with a python backend, and will not be interactive on the docs website.""",
    ],
)

We use the reset method of a plot to update its content in-place, inside an async function containing a while loop, using [sleep](bylight?dir=up&match=asyncio.sleep(...)) to control the frame rate. To avoid interference with Jupyter comms, we use [ensure_future](bylight?dir=up&match=asyncio.ensure_future(...)) to run the function in a new thread.

Let's make it interactive, using ipywidgets sliders to control frequency and amplitude:

Now, in our animation loop we use the slider values to compute the y value: