Simplicity
Simplicity

Reputation: 48916

Matplotlib - Why does the figure get saved twice?

I'm trying to plot and save a figure using Matplotlib as follows:

plt.plot(number_of_epochs, accuracy, 'r', label='Training accuracy')
plt.plot(number_of_epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend()
plt.savefig('accuracy.png')

plt.plot(number_of_epochs, loss, 'r', label='Training loss')
plt.plot(number_of_epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.savefig('loss.png')

The first figure accuracy.png gets saved fine. However, for loss.png, it contains both the accuracy figure and the loss figure. How can I keep only the loss.png figure in the latter case?

Thanks.

Upvotes: 0

Views: 247

Answers (2)

Simplicity
Simplicity

Reputation: 48916

Using plt.close() before the second plot would do the job.

Upvotes: 1

Venkatachalam
Venkatachalam

Reputation: 16966

Just add plt.figure() inbetween the two plots. It helps you to plot in new figure, instead of plotting on the previous figure. If you don't want first figure, use plt.close().

Try this

plt.plot(number_of_epochs, accuracy, 'r', label='Training accuracy')
plt.plot(number_of_epochs, val_acc, 'b', label='Validation accuracy')
plt.title('Training and validation accuracy')
plt.legend()
plt.savefig('accuracy.png')

plt.figure()
plt.plot(number_of_epochs, loss, 'r', label='Training loss')
plt.plot(number_of_epochs, val_loss, 'b', label='Validation loss')
plt.title('Training and validation loss')
plt.legend()
plt.savefig('loss.png')

Upvotes: 1

Related Questions