How do I send NLTK plots to files?
Question: I'm using NLTK to create dispersion plots and do a few other things. Trouble
is, I have to manually close the window that creating a dispersion plot opens
to get the code to continue running. How can I send the plot to a file and
keep the script moving? I assume I'll have the same problem with other plots.
I can see from the [NLTK
source](http://www.nltk.org/_modules/nltk/draw/dispersion.html) that
`dispersion_plot` already includes `pylab.show()` so maybe this isn't possible
without writing my own plotting function?

Here's my code that stops at line 2 until I close the Python window that opens
with the plot.

    
    
    1 # do some analysis
    2 disp_plot(days, key_terms)
    3 diversity_table(days, "Day")
    

Here's the `disp_plot` function:

    
    
    # dispersion plots for search terms
    def disp_plot(texts, terms):
        concat_text = ''.join(texts.values())
        tokens = nltk.word_tokenize(concat_text)
        text = nltk.Text(tokens)
        text.dispersion_plot(terms)
    


Answer: I ran into the same problem and solved it by reassigning pylab.show to my own
function. You might do something like this:

    
    
    import pylab
    
    counter = 0
    def filename_generator():
        global counter
        to_return = 'myfig{0}.png'.format(counter)
        counter += 1
        return to_return
    
    def my_show():
        return pylab.savefig(filename_generator())
    

and change your disp_plot() to look like

    
    
    def disp_plot(texts, terms):
        concat_text = ''.join(texts.values())
        tokens = nltk.word_tokenize(concat_text)
        text = nltk.Text(tokens)
        pylab_orig_show = pylab.show
        pylab.show = my_show
        text.dispersion_plot(terms)
        pylab.show = pylab_orig_show
    

Some would argue about the global, but this is just a quick hack to get the
library to do what you want.

