I have a main script and a library with a function. The idea is that from some data, it generates a graphic representation and saves an image of the graph in .png Everything works fine, except that the .png image it generates is a blank image. Also, after displaying the graph, the console tells me:
matplotlib.figure.Figure at 0xc8f37b8
Main Script:
import f02_graphs as gr
y = [1, 7, 3, 4]
x = [0, 1, 2, 3]
d = "Z:\Trabajos\Python 3\proyectos\p00_banco_de_pruebas"
gr.one_line(x, y, save=d, title='Kosovo')
Library function:
import matplotlib.pyplot as plt
def one_line(x, y, show=True, save=False, title="Title", xlab="Abscissa",
ylab="Ordinate"):
# Representa con una linea la lista de datos pasada como parametro.
#
# x: almacena los datos de la coordenada x.
# show: determina si se muestra la grafica por pantalla.
# save: almacena el directorio para guardar la grafica como una
# imagen. Si su valor es None, no se guarda la imagen.
# title: titulo de la grafica.
# xlab: etiqueta del eje x.
# ylab: etiqueta del eje y.
#
# Creamos la grafica.
plt.figure()
# Dibujamos la representacion de los datos.
plt.plot(x, y)
# Añadimos el titulo.
plt.title(title)
# Añadimos las etiquetas a los ejes.
plt.xlabel(xlab)
plt.ylabel(ylab)
# Añadimos una rejilla.
plt.grid(True)
# Ajustamos los ejes a la zona con datos.
plt.axis('tight')
#
# Mostramos la imagen de la grafica por pantalla.
if show:
plt.show()
#
# Guardamos la imagen en un directorio introducido por el usuario.
if save:
plt.savefig('dragon.png')
However, if instead of calling the function, I do it all in the main script, it saves without a problem. But I want to do it by calling a function inside a library.
How can I solve this problem?
PS: I work with Spyder 3
Matplotlib considers figures and axes "current" to be everything that has not been displayed using
show
. When it is calledplt.show()
, everything that was pending to be displayed is reset, creating a new blank figure. I don't know if you have noticed that if you don't show the figure it is saved correctly. We can find a notice about it in the official documentation :which we could translate something like this:
To solve the problem you can:
Call first a
plt.savefig
and then a byplt.show
reversing the order of the conditionals.Or use a variable to store the reference to the instance
matplotlib.figure.Figure
you want to save:Just reverse the order of the
if
. And add the path where you will save the image. For example:Instead of
Write: