Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Matplotlib - saved images getting overwritten while using for loop

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 , Figure 2 , Figure 3

What might be the problem? Kindly help me with this. I am new to matplotlib.

like image 552
Jeril Avatar asked Mar 12 '23 15:03

Jeril


1 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')
like image 172
mprat Avatar answered Mar 15 '23 04:03

mprat