Is there a way to detach matplotlib plots so that the computation can continue? Is there a way to detach matplotlib plots so that the computation can continue? python python

Is there a way to detach matplotlib plots so that the computation can continue?


Use matplotlib's calls that won't block:

Using draw():

from matplotlib.pyplot import plot, draw, showplot([1,2,3])draw()print('continue computation')# at the end call show to ensure window won't close.show()

Using interactive mode:

from matplotlib.pyplot import plot, ion, showion() # enables interactive modeplot([1,2,3]) # result shows immediatelly (implicit draw())print('continue computation')# at the end call show to ensure window won't close.show()


Use the keyword 'block' to override the blocking behavior, e.g.

from matplotlib.pyplot import show, plotplot(1)  show(block=False)# your code

to continue your code.


It is better to always check with the library you are using if it supports usage in a non-blocking way.

But if you want a more generic solution, or if there is no other way, you can run anything that blocks in a separated process by using the multprocessing module included in python. Computation will continue:

from multiprocessing import Processfrom matplotlib.pyplot import plot, showdef plot_graph(*args):    for data in args:        plot(data)    show()p = Process(target=plot_graph, args=([1, 2, 3],))p.start()print 'yay'print 'computation continues...'print 'that rocks.'print 'Now lets wait for the graph be closed to continue...:'p.join()

That has the overhead of launching a new process, and is sometimes harder to debug on complex scenarios, so I'd prefer the other solution (using matplotlib's nonblocking API calls)


matomo