Diego
Diego

Reputation: 233

Matplotlib doesn't forget previous data when saving figures with savefig

import matplotlib.pyplot as plt
plt.plot([1,2,3],[1,2,3],'ro')
plt.axis([-4,4,-4,4])
plt.savefig('azul.png')
plt.plot([0,1,2],[0,0,0],'ro')
plt.axis([-4,4,-4,4])
plt.savefig('amarillo.png')

Output:

azul amarillo

Why does this happen and how to solve?

Upvotes: 0

Views: 1721

Answers (1)

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339062

What you see is a completely expected behaviour. You can plot as many data as often as you want to the same figure, which is very often very useful.

If you want to create several figures in the same script using the matplotlib state machine, you need to first close one figure before generating the next.

So in this very simple case, just add plt.close() between figure creation.

import matplotlib.pyplot as plt
plt.plot([1,2,3],[1,2,3],'bo')
plt.axis([-4,4,-4,4])
plt.savefig('azul.png')
plt.close()
plt.plot([0,1,2],[0,0,0],'yo')
plt.axis([-4,4,-4,4])
plt.savefig('amarillo.png')

Upvotes: 4

Related Questions