0

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.

Simplicity
  • 47,404
  • 98
  • 256
  • 385

2 Answers2

1

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')
Venkatachalam
  • 16,288
  • 9
  • 49
  • 77
1

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

Simplicity
  • 47,404
  • 98
  • 256
  • 385