I am new new in Python/Django and I try to create a website which generates plots. To generate plots I use matplotlib.
When I run the page first time everything is ok, but after refresh in result I get wrong plot (composed of new and old plot).
Here the code:
from pylab import *
...
#prepare values and labels
values = []
labels = []
values.append(float(user.playcount)/sum*100)
labels.append(user.name)
for friend in friends:
friend = friend.getInfo()
values.append(float(friend.playcount)/sum*100)
labels.append(friend.name)
# create figure
figure(1)
# set some parameters
params = { 'axes.labelsize': 6, 'text.fontsize': 6, 'font.size': 6, 'legend.fontsize': 6, 'xtick.labelsize': 6, 'ytick.labelsize': 6,}
rcParams.update(params)
# draw, add legend and save
pie(values, labels=labels, shadow=False)
l = legend(loc='lower center', ncol= 5, bbox_to_anchor=(0.5, -0.25))
l.get_frame().set_alpha(0.0)
savefig('media/images/3.png', dpi=100, transparent=True)
#close(1)
If I uncomment close(1) instruction there will problem with refresh page because application will get stuck on figure() instruction.
Could anyone tell me where is the problem? I think there is something wrong with figure disposing but I don’t have idea what exactly.
I think you would benefit from using the
cla()axes method, which clears the axes. You can do this at the top of your script before anything is done; even before the first plot. I would use this instead ofclose(), because then the second time around the figure will not exist. So I would replace thefigure(1)line withThis sets the figure to figure 1, and then gets the current axes (
gca()) and then clears it withcla(). Here’s a script I ran independantly of django, that worked for me and emulates what I think you are trying to do:You probably can get away with only one line; just having this worked for me:
But it’s a bit clearer perhaps the other way.