Save multiple figures in a loop - Python

Asked

Viewed 2,226 times

5

I’m using python for experimental data analysis. 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 the different charts at the end of the loop.

This works great for just one type of Plot in the loop. As I want different Plots, this method does not work because there is overlapping of two charts.

It is possible to save different figures in one loop only?

  • 4

    Hey there, Eduardo. What you want is probably possible if you create a blank image for each new group, but it would be interesting for you to post the code so we could analyze.

  • 1

    It is strongly recommended to always show a minimal example of what one is trying to do.

1 answer

4

You haven’t shown your code, but assuming you’re using it matplotlib.pyplot as in the tutorial, I suggest each new figure and/or each new subplot is stored in a dict, so that 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:

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

  • Replace the methods iterar_arquivos, escolher_grupos and escolher_subplots by its particular logic.

  • By calling matplotlib.pyplot.image passing the same name of the image you created earlier, 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 current image, creating subplots (all of the SOEN).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.