Matplotlib (pyplot) savefig outputs blank image
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Take control of your privacy with Proton's trusted, Swiss-based, secure services.
Choose what you need and safeguard your digital life:
Mail: https://go.getproton.me/SH1CU
VPN: https://go.getproton.me/SH1DI
Password Manager: https://go.getproton.me/SH1DJ
Drive: https://go.getproton.me/SH1CT
Music by Eric Matyas
https://www.soundimage.org
Track title: The World Wide Mind
--
Chapters
00:00 Matplotlib (Pyplot) Savefig Outputs Blank Image
00:27 Accepted Answer Score 509
01:25 Answer 2 Score 278
01:41 Answer 3 Score 3
02:10 Answer 4 Score 41
02:21 Thank you
--
Full question
https://stackoverflow.com/questions/9012...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #image #matplotlib #figure
#avk47
ACCEPTED ANSWER
Score 509
First, what happens when T0 is not None? I would test that, then I would adjust the values I pass to plt.subplot(); maybe try values 131, 132, and 133, or values that depend whether or not T0 exists.
Second, after plt.show() is called, a new figure is created. To deal with this, you can
Call
plt.savefig('tessstttyyy.png', dpi=100)before you callplt.show()Save the figure before you
show()by callingplt.gcf()for "get current figure", then you can callsavefig()on thisFigureobject at any time.
For example:
fig1 = plt.gcf()
plt.show()
plt.draw()
fig1.savefig('tessstttyyy.png', dpi=100)
In your code, 'tesssttyyy.png' is blank because it is saving the new figure, to which nothing has been plotted.
ANSWER 2
Score 278
plt.show() should come after plt.savefig()
Explanation: plt.show() clears the whole thing, so anything afterwards will happen on a new empty figure
ANSWER 3
Score 41
change the order of the functions fixed the problem for me:
- first Save the plot
- then Show the plot
as following:
plt.savefig('heatmap.png')
plt.show()
ANSWER 4
Score 3
let's me give a more detail example:
import numpy as np
import matplotlib.pyplot as plt
def draw_result(lst_iter, lst_loss, lst_acc, title):
plt.plot(lst_iter, lst_loss, '-b', label='loss')
plt.plot(lst_iter, lst_acc, '-r', label='accuracy')
plt.xlabel("n iteration")
plt.legend(loc='upper left')
plt.title(title)
plt.savefig(title+".png") # should before plt.show method
plt.show()
def test_draw():
lst_iter = range(100)
lst_loss = [0.01 * i + 0.01 * i ** 2 for i in xrange(100)]
# lst_loss = np.random.randn(1, 100).reshape((100, ))
lst_acc = [0.01 * i - 0.01 * i ** 2 for i in xrange(100)]
# lst_acc = np.random.randn(1, 100).reshape((100, ))
draw_result(lst_iter, lst_loss, lst_acc, "sgd_method")
if __name__ == '__main__':
test_draw()
