matplotlib pyplot show capture image
Question: In a python interactive session the following code is run:

    
    
    import matplotlib.pyplot as plt
    plt.plot([1,2,3])
    plt.show()
    

how do I let show() not block and not actually show the image, but instead
store it in a file? I can not change the code to `plt.savefig('figure.png')`.
(There is a very good reason for this, I can explain if interested.)

The way to go seems to be specifying a custom backend renderer but so far no
success. Is it possible to take an existing backend renderer and change the
show() method to save to a file? (Lets say "figure%d.png" with %d the amount
of times show() has been called so far.)

Other suggestions next to a custom backend renderer are welcome as well. In
IPython notebook if you execute plt.show(), it manages to take the image and
place it beneath the active code block. How's that done?


Answer: You could use the solution from
[here](http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html)
for creating a figure without a gui. This uses `FigureCanvasAgg` (which is the
gui built by [default](http://stackoverflow.com/questions/4931376/generating-
matplotlib-graphs-without-a-running-x-server), you could probably use a
different one). The show in pyplot can then be monkey patched,

    
    
    import matplotlib.pyplot as plt
    from matplotlib.backends.backend_agg import FigureCanvasAgg
    
    def show(fig=None):
    
        if fig == None:
            fig = plt.gcf()
        canvas = FigureCanvasAgg(fig)
        canvas.print_figure("./out.png", dpi=80)
    
    plt.show = show    
    plt.plot([1,2,3])
    plt.show()
    

Not sure if this avoid the problem you have with savefig?

