0
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?

1 Answer 1

4

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')
Sign up to request clarification or add additional context in comments.

2 Comments

I think the more common method used is to do plt.figure(), which creates a new figure and keeps the first figure alive (in fact, plt.plot implicitly calls plt.figure when no figure is active). Of course in this case, both methods result in effectively the same outcome.
Thank you so much. as a new member to ML, you saved my time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.