Search code examples
pythonmatplotlibplotflush

How to get python matplotlib to flush all graphics


I'm playing around with some large data sets that change as a function of some parameter i can control. I now want to plot the distributions of my data in sub-plots in the same figure. However, since the data is quite large it takes a while to construct the histograms.

So, I would like the sub-plots to be drawn as they are finished a bit like below.

import matplotlib.pyplot as plt
import numpy as np
import numpy.random as npr

Ne=10
MC=1000000
f1d,f2d = plt.figure(),plt.figure()
for Part in range(Ne):
    datax=npr.normal(size=MC)+4*Part/Ne ##Simulates my big data
    datay=npr.normal(size=MC) ##Simulates my big data
    ###The 1d histogram
    sf1d = f1d.add_subplot(1,Ne,Part+1,)    
    sf1d.hist(datax,bins=20,normed=True,histtype='stepfilled',alpha=0.5)
    sf1d.hist(datay,bins=20,normed=True,histtype='stepfilled',alpha=0.5)
    plt.show(block=False)

    ###Some flush argument()

    ###The 2d histogram
    sf2d = f2d.add_subplot(1,Ne,Part+1)
    sf2d.hist2d(datax,datay,bins=20,normed=True)
    plt.show(block=False)

    ###Some flush argument()

However, python will not draw all of the sub-plots in real-time, but will buffer these until the loop has completed. How do I force matplotlib to flush the sub-plots immediately?


Solution

  • From the matplotlib docs:

    matplotlib.pyplot.draw()

    Redraw the current figure.

    This is used in interactive mode to update a figure that has been altered, but not automatically re-drawn.

    A more object-oriented alternative, given any Figure instance, fig, that was created using a pyplot function, is:

    fig.canvas.draw_idle()