Minimum working example
I expect the following to show a plot, but i see no plot and the interpreter just hangs (my backend reports itself as TkAgg
).
import matplotlib.pyplot as plt
from threading import Thread
def plot():
fig, ax = plt.subplots()
ax.plot([1,2,3], [1,2,3])
plt.show()
def main():
thread = Thread(target=plot)
thread.setDaemon(True)
thread.start()
print 'Done'
How do I get the plot to display?
Context
I am running a simulation with lots iterations and would like to update my plot every 1000 iterations so that I can monitor how my simulation is evolving.
Psuedocode below:
iterations = 100000
for i in iterations:
result = simulate(iteration=i)
if not i % 1000:
# Update/redraw plot here:
# Add some lines, add some points, reset axis limits, change some colours
Having the plot in the main thread causes the plot GUI to hang/crash presumably because I have other work going on. So the idea was to do the plotting in a separate thread.
I have seen suggestions (e.g. here) to use a process rather than a thread. But then I cannot manipulate the figure or axes to add lines etc while my simulation runs because the figure object is in the remote process.
Edit
I'm not convinced this question is a duplicate of another one because that question deals with why the pyplot
api cannot be used to manipulate two different plots that are each on a separate thread. It is because race conditions arising from executing two plots simultaneously prevents pyplot
from determining which figure is the current figure.
However, I only have 1 plot and so pyplot
only ever has a single and unique current figure.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…