How to save Python figure with matplotlib?

3

Any figure I try to save in Jupyter Notebook saves a blank file, what kind of error can be occurring, since it does not acknowledge any errors?

import numpy as np
import matplotlib.pyplot as plt


data1 = [10,5,2,4,6,8]
data2 = [ 1,2,4,8,7,4]
x = 10*np.array(range(len(data1)))

plt.plot( x, data1, 'go') # green bolinha
plt.plot( x, data1, 'k:', color='orange') # linha pontilha orange

plt.plot( x, data2, 'r^') # red triangulo
plt.plot( x, data2, 'k--', color='blue')  # linha tracejada azul

plt.axis([-10, 60, 0, 11])
plt.title("Mais incrementado")

plt.grid(True)
plt.xlabel("eixo horizontal")
plt.ylabel("Eixo y")
plt.show()
plt.savefig('teste.png', format='png')
    
asked by anonymous 16.06.2018 / 06:24

1 answer

2

When you do plt.show() , the figure is reset to prepare another graph. So calling savefig results in the blank image you got.

You have two options:

  • Call savefig before show :

    plt.savefig('teste.png', format='png')
    plt.show()
    

.

  • Use plt.gcf() (from "get current figure") to save your chart to a variable, and save it at any time.

    fig = plt.gcf()
    plt.show()
    fig.savefig('teste.png', format='png')
    
16.06.2018 / 15:57