Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matplotlib - Only show one figure

So I'm got a few plots that my code generates. I want to save all of them, but I only want to display one. I can do the save part just fine, but getting only one to display is proving a pain.

Been going round in circles with trying to achieve this. The closest I got was to clear all but one of the figures, but they all were displayed when I tried to show just one. Starting to think it's either something very simple I'm overlooking or else it's not possible.

Anyone know how to achieve this?

Edit: Added sample code. Apologies for not doing so originally.

    fig1 = plt.figure(1)
    plt.plot([0, 1, 2, 3, 4], [0, 1, 2, 3, 4], label="Test", color='g')
    plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16],  label="Other Test",  color='r')
    plt.grid(True)

    fig1.savefig('Foo1.png')

    fig2 = plt.figure(2)
    plt.plot([0, 1, 2, 3, 4], [0, 5, 1, 9, 2], label="Test 2", color='g')
    plt.plot([0, 1, 2, 3, 4], [0, 10, 50, 0, 10],  label="Other Test 2",  color='r')
    plt.grid(True)

    fig2.savefig('Foo2.png')

    plt.show()
like image 244
Steve Avatar asked May 07 '15 19:05

Steve


1 Answers

You can close each figure just after you save it using plt.close(). Just be sure to not make a close statement after the last figure.

Your code will look like this:

fig1 = plt.figure(1)
plt.plot([0, 1, 2, 3, 4], [0, 1, 2, 3, 4], label="Test", color='g')
plt.plot([0, 1, 2, 3, 4], [0, 1, 4, 9, 16],  label="Other Test",  color='r')
plt.grid(True)

fig1.savefig('Foo1.png')
# add plt.close() after you've saved the figure
plt.close()

fig2 = plt.figure(2)
plt.plot([0, 1, 2, 3, 4], [0, 5, 1, 9, 2], label="Test 2", color='g')
plt.plot([0, 1, 2, 3, 4], [0, 10, 50, 0, 10],  label="Other Test 2",  color='r')
plt.grid(True)

fig2.savefig('Foo2.png')

plt.show()
like image 89
mishaF Avatar answered Sep 24 '22 02:09

mishaF