Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python saving empty plot [duplicate]

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')
like image 985
Osama Arshad Dar Avatar asked Jul 06 '18 05:07

Osama Arshad Dar


3 Answers

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
like image 58
Reblochon Masque Avatar answered Sep 22 '22 18:09

Reblochon Masque


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()
like image 40
Luca Cappelletti Avatar answered Sep 19 '22 18:09

Luca Cappelletti


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.

like image 28
hondvryer Avatar answered Sep 19 '22 18:09

hondvryer