Home > Enterprise >  Matplotlib: Is there a way so that we can see and work with plot result while the routines after the
Matplotlib: Is there a way so that we can see and work with plot result while the routines after the

Time:03-19

Is there a way so that we can see and work with the plot result (figure and axes) while the routines after the fig.show() is being processed by Python?

For example, running the code below, Python shows the figure window but not the plot (it only shows white background, lagging) while the for loop is being processed. Only after the whole code finished I can see the plot and interactively work with it.

import matplotlib.pyplot as plt


fig, ax = plt.subplots()

ax.plot([1,2,3]); fig.show()

#I want the plot to be visible and explorable,
# while the for loop below is in process (or any other kind of routine)
for i in range(10000):
    print(i)

Screenshot of the result (you can see the plot is lagging, only blank white):

enter image description here

CodePudding user response:

You could use a combination of a separate python process (via multiprocessing) and the blocking behaviour of plt.show() to achieve the desired result:

import matplotlib.pyplot as plt
import time
from multiprocessing import Process

def show_plot(data):
    fig, ax = plt.subplots()
    ax.plot(data)
    plt.show()

def do_calculation():
    for i in range(100):
        print(i)
        time.sleep(0.1)

if __name__ == '__main__':
    p = Process(target=show_plot, args=([1,2,3],))
    p.start() # start parallel plotting process
    do_calculation()
    p.join() # the process will terminate once the plot has been closed
  • Related