Matplotlib (pyplot) savefig displays a blank image

I am trying to save the graphs that I do using matplotlib; however, images are kept blank.

Here is my code:

plt.subplot(121) plt.imshow(dataStack, cmap=mpl.cm.bone) plt.subplot(122) y = copy.deepcopy(tumorStack) y = np.ma.masked_where(y == 0, y) plt.imshow(dataStack, cmap=mpl.cm.bone) plt.imshow(y, cmap=mpl.cm.jet_r, interpolation='nearest') if T0 is not None: plt.subplot(123) plt.imshow(T0, cmap=mpl.cm.bone) #plt.subplot(124) #Autozoom #else: #plt.subplot(124) #Autozoom plt.show() plt.draw() plt.savefig('tessstttyyy.png', dpi=100) 

And tessstttyyy.png is empty (also tried with .jpg)

+120
python matplotlib image figure
Jan 26 '12 at 12:30
source share
3 answers

First, what happens when T0 is not None ? I would experience this, then I would set the values ​​I pass to plt.subplot() ; perhaps try values ​​131, 132, and 133, or values ​​depending on whether or not T0 exists.

Secondly, after calling plt.show() , a new shape is created. To handle this, you can

  • Call plt.savefig('tessstttyyy.png', dpi=100) before you call plt.show()

  • Save the figure before show() by calling plt.gcf() to "get the current digit", then you can call savefig() on this Figure object at any time.

For example:

 fig1 = plt.gcf() plt.show() plt.draw() fig1.savefig('tessstttyyy.png', dpi=100) 

In your code, "tesssttyyy.png" is empty because it saves a new shape on which nothing was built.

+193
Jan 26 '12 at 1:05
source share

plt.show() should appear after plt.savefig()

+62
Nov 17 '17 at 3:57
source share

let me give a more detailed 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() 

enter image description here

0
Jul 20 '18 at 9:33
source share



All Articles