1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] How to forcefully trigger updates for dynamic plots in Google Colab without user...

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024.

  1. Stack

    Stack Membro Participativo

    I'm trying to create responsive dynamic plots in Google Colab, but I'm running into performance issues with the updates.

    For a minimal example, I made a simple scatter plot of random values with a changing title. Initially, the plot updates smoothly for the first few frames, but it quickly starts to slow down or even freeze completely. A strange workaround I've discovered is that spam-clicking the figure keeps the updates running more consistently, roughly every second.

    I'm wondering if there's a way to "simulate" this spam-clicking behavior or send some kind of event to force Colab to update the figure more reliably, without requiring direct user interaction. So far, I haven't found anything that works well.

    I'm open to any suggestions, even hacky workarounds, as long as they help keep the plot updates responsive and prevent Colab from "putting the plot to sleep."

    [​IMG] https://colab.research.google.com/drive/1n8xjt3ZtmeRmW5Usl_gcCoSHy1SGEWBy?usp=sharing

    %pip install ipympl

    from google.colab import output
    output.enable_custom_widget_manager()
    %matplotlib ipympl

    import matplotlib.pyplot as plt
    import numpy as np
    import threading
    import time
    figure, ax = plt.subplots()
    line = ax.plot([],[], 'o')
    ax.set_xlim(0,100)
    ax.set_ylim(0,1)

    figure._canvas_callbacks._signals += ["fake_event"]
    def wtf_event(*args,**kwargs):
    print(flush=True, end="")
    # print(args,kwargs)
    figure.canvas.mpl_connect('fake_event', wtf_event)

    def work1(figure,ax,line):
    total = 100
    for i in range(total):
    X,Y = np.arange(100), np.random.rand(100) # data
    figure.suptitle(i) # update title
    line[0].set_data(X, Y) # update plot

    figure.canvas.flush_events()
    # figure.canvas.draw() # causes issues, if the delay is too long doesn't draw at all
    figure.canvas.draw_idle()

    # plt.pause(0.2) # throws errors
    time.sleep(0.2) # actual display can take from instantly to 30 seconds (or more) in colab,
    # colab also required cell to be "actively in focus" to update, repeatedly clicking on the plot "helps" it update (about 1 second)

    figure.canvas.callbacks.process("fake_event")

    thread = threading.Thread(target=work1, args=(figure,ax,line))
    thread.start()

    Continue reading...

Compartilhe esta Página