5

EDIT: This question is a duplicate. Original question's link is posted above.

I am using Python to plot a set of values which are showing good on the Python terminal (using Jupyter NoteBook) but when I save it, the saved file when opened shows an empty (completely white) photo. Here's my code:

import matplotlib.pyplot as plt
plt.plot([1,3,4])
plt.show()
plt.savefig('E:/1.png')
Osama Dar
  • 404
  • 5
  • 15

3 Answers3

13

You should save the plot before closing it: indeed, plt.show() dislays the plot, and blocks the execution until after you close it; hence when you attempt to save on the next instruction, the plot has been destroyed and can no longer be saved.

import matplotlib.pyplot as plt
plt.plot([1,3,4])
plt.savefig('E:/1.png')   # <-- save first
plt.show()                # <-- then display
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
4

When you execute the show, plt clears the graph. Just invert the execution of show and savefig:

import matplotlib.pyplot as plt
plt.plot([1,3,4])
plt.savefig('E:/1.png')
plt.show()
Luca Cappelletti
  • 2,485
  • 20
  • 35
2

I think the plt.show() command is "using up" the plot object when you call it. Putting the plt.savefig() command before it should allow it to work.

Also, if you're using Jupyter notebooks you don't even need to use plt.show(), you just need %matplotlib inline somewhere in your notebook to have plots automatically get displayed.

hondvryer
  • 442
  • 1
  • 3
  • 18