I am working on a project in django
which I use the matplotlib
. In theory I have created a filter where you choose the day and and "node" that you want to graph and with this information a script is executed python
that together with pandas
and matplotlib
creates a graph.
The values of "node" and "dia" arrive correctly to the script, and this generates the graph well, the only thing wrong is that instead of overwriting the old image (with the previous graph) it draws the new lines on top. Below is an image of how it looks.
As you can see, each line is equivalent to a different day, because the different tests that I have done have been superimposed. Can someone tell me where I'm wrong?
Below I attach code
def bateria2(node, day):
csv_path = os.path.join(os.path.dirname(__file__), '..\\data\\csv\\dataframe.csv')
df = pd.read_csv(csv_path)
mes, anyo = 12, 2019
new_df = df[(df['Dia'] == day) & (df['Mes'] == mes) & (df['Año'] == anyo) & (df['Node name'] == node)]
if len(new_df) > 0:
#os.remove('static\\img\\bateria2.png')
x = new_df['Hora[UTC]'].tolist()
y = new_df['Bateria'].tolist()
title = 'Carga/Descarga de la batería día '+str(day)+'/'+str(mes)+'/'+str(anyo)+' de '+str(node)
plt.title(title)
plt.xlabel('Hora [UTC]')
plt.ylabel('Batería')
#plt.legend((y)(node))
plt.plot(x,y)
plt.xticks(x, rotation='vertical')
plt.savefig('static\\img\\bateria2.png',transparent=True)
return 1
else:
return 0
Basically it is to access the file .csv
that contains the info, filter according to the data that I want. And if the new generated dataframe has data, create the graph to finally save it.
Regards thank you very much.
After
plt.savefig(...)
you have to explicitly delete the plot withplt.clf()
.When using matplotlib outside of django, you have to do
plt.show()
to display the plot in a window. When closing the window, matplotlib automatically deletes the entire plot. (That's why if you want to save an image, do it before callingplt.show()
.) Withoutplt.show()
matplotlib you don't know if you want to keep adding to the plot or start a new one.