Save multiple figures in a loop - Python

4

I'm using python to analyze experimental data. I have in a folder several data files that, in the script, are grouped according to some criteria. I use a loop to read all the files in the folder, and within the loop, data from the same group is plotted on the same chart, saving different graphs at the end of the loop.

This works great for just one type of plot in the loop. Since I want different plots, this method does not work because there are two graphs overlapping.

Is it possible to save different shapes in a single loop?

    
asked by anonymous 27.02.2014 / 22:40

1 answer

3

You did not show your code, but assuming you're using matplotlib.pyplot as in the tutorial , I suggest each new picture and / or each new subplot is stored in dict , so you can access it again whenever necessary:

imagens = {}
def obter_subplot(imagem, subplot, *args, **kwargs):
    if not imagem in imagens:
        imagens[imagem] = { '__imagem':matplotlib.pyplot.figure(imagem) }
    if not subplot in imagens[imagem]:
        imagens[imagem][subplot] = imagens[imagem].__imagem.add_subplot(*args,**kwargs)
    return imagens[imagem][subplot]

for arq in iterar_arquivos():
    for grupo in escolher_grupos(arq):
        for subplot,args,kwargs in escolher_subplots(arq, grupo):
            plt = obter_subplot(grupo, subplot, *args, **kwargs)
            # usar plt como se fosse matplotlib.pyplot

for imagem in imagens.keys():
    matplotlib.pyplot.image(imagem) # Troca a imagem corrente
    matplotlib.pyplot.savefig(...) # Salva a imagem corrente num arquivo

Clarifying:

  • dict imagens maps the name of each image to another dict , which maps the name of a subplot to the specific subplot. The parameters args and kwargs allow you to customize the creation of the subplot (eg for subplot(2,1,1) use args=[2,1,1] and kwargs=None );

  • Replace the methods iterar_arquivos , escolher_grupos and escolher_subplots with their particular logic.

  • When calling matplotlib.pyplot.image passing the same name as the image you created previously, it changes it to the "current image". This allows you to save it to a file in the usual way.

Sources: saving image , assigning the image current , creating subplots (all from SOEN).

    
04.03.2014 / 03:36