Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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.

share|improve this question
up vote 2 down vote accepted

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')
share|improve this answer
    
Maybe you want to place plt.clf() at the end of the loop? I have not checked, but IDK what happens when you call clf() with no figure to clear? – Reblochon Masque Apr 9 at 5:12
    
Nothing happens, it clears an empty figure. – mprat Apr 9 at 5:13
    
@mprat Thanks a lot. It is now giving me as I wanted – Jeril Apr 9 at 5:14

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.