How to save figure in Python with matplotlib?

Asked

Viewed 6,892 times

4

Any figure I try to save in Jupyter Notebook saves a blank file, what kind of error might be occurring as it does not accuse any error?

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')

1 answer

4


When you do plt.show(), the figure is zeroed to prepare another graph. So, call savefig results in the blank image you obtained.

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')
    
  • Now yes, thank you. Another question, has how to increase the area being saved? Why in another figure is the legend being cut when saved.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.