Matplotlib (pyplot) savefig outputs blank image


I am trying to save plots I make using matplotlib; however, the images are saving blank.

Here is my code:


y = copy.deepcopy(tumorStack)
y = == 0, y)

plt.imshow(y,, interpolation='nearest')

if T0 is not None:


plt.savefig('tessstttyyy.png', dpi=100)

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

Asked By: tylerthemiler



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 is called, a new figure is created. To deal with this, you can

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

  2. Save the figure before you show() by calling plt.gcf() for “get current figure”, then you can call savefig() on this Figure object at any time.

For example:

fig1 = plt.gcf()
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.

Answered By: Yann should come after plt.savefig()

Explanation: clears the whole thing, so anything afterwards will happen on a new empty figure

Answered By: JAG2024

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.savefig(title+".png")  # should before method

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__':

enter image description here

Answered By: Jayhello

change the order of the functions fixed the problem for me:

  • first Save the plot
  • then Show the plot

as following:

Answered By: Behzad Sezari

Calling savefig before show() worked for me.

fig ,ax = plt.subplots(figsize = (4,4))
sns.barplot(x='sex', y='tip', color='g', ax=ax,data=tips)
sns.barplot(x='sex', y='tip', color='b', ax=ax,data=tips)
ax.legend(['Male','Female'], facecolor='w')

Answered By: Krish
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.