Saved images getting overwritten while using for loop

Question:

I am having one big list which has six small list’s. These six small lists are used as the slice values while generating a pie chart using matplotlib.

f_c = [[4, 1, 0, 1, 0], 
       [4, 1, 0, 1, 0], 
       [4, 1, 0, 1, 0], 
       [4, 0, 2, 0, 0], 
       [4, 0, 2, 0, 0], 
       [4, 1, 0, 0, 1]]

I have another one list which has the labels

titles = ['Strongly Agree', 'Agree', 'Neutral',
          'Disagree', 'Strongly Disagree']

Now, I am using a for loop to save the generated pie-charts. The code is as follows:

for i, j in zip(f_c, lst):
    pie(i,
    labels=titles,
    shadow=True)
    savefig(j + '.png')

‘lst’ is a list that is having file names, and is used to save the the pie charts.

I am able to generate the pie charts, but the charts and labels are getting overwritten. Only the first figure is coming correctly, rest of the figures are getting overwritten. When I did it manually all the figures were generating correctly, but if I put it in a loop it is not getting saved correctly (it’s getting overwritten). The following are the generated images (only 3):

[![Figure 1][1]][1]

, [![Figure 2][2]][2]
, [![Figure 3][3]][3]

What might be the problem? Kindly help me with this. I am new to matplotlib.
[1]: https://i.stack.imgur.com/WGJcV.png
[2]: https://i.stack.imgur.com/rwOfF.png
[3]: https://i.stack.imgur.com/S6VAM.png

Asked By: Jeril

||

Answers:

It’s a good idea to clear the figure you’re working with before trying to generate a new figure, just to be clear that you are starting from a blank slate. You clear with with plt.clf(), which stands for “clear figure”.

Not directly related to your question, but it’s also a good idea in Python to not do from matplotlib import *, because it might overwrite other methods you have locally. Using meaningful variable names also help.

Something like this will work:

import matplotlib.pyplot as plt
for fig, fig_name in zip(fig_data, fig_names):
    plt.clf()
    plt.pie(fig, labels=titles, shadow=True)
    plt.savefig(fig_name + '.png')
Answered By: mprat
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.