问题
In google-colab:
I have a python code which uses a class from another file. The class has a method which has the following code:
def callbacks():
plt.style.use("ggplot")
plt.figure()
plt.plot(N, self.H["loss"], label="train_loss")
#code continues
plt.legend()
#save the fig
plt.savefig(self.figPath)
plt.close()
This method( part of "callbacks") is invoked every time in each epoch when I run the code of the main file.:
model.fit(trainX, trainY, validation_data=(testX, testY),
batch_size=64, epochs=100, callbacks=callbacks, verbose=1)
But I couldn't get the figure in google colab but it is being saved at the correct location(as expected) What I did but failed are:
- using plt.show() before plt.savefig(..)
- runnning
%matplotlib inline
before the start of the code
What should be done to dislpay the plot as the epochs are run? The reason I want them to run as the epochs are displayed is because it is taking some time to update the figure on google drive
回答1:
Once plt.close()
is called, the figure is closed. The only way to display the figure after calling the above code is to remove plt.close()
from the code you are calling.
As a last resort, if there's no way to edit this code, you could monkey-patch the close function before calling the code in question; for example:
plt.close = lambda: None
but be aware that this overriding core functionality like this is a very bad idea and will likely have unintended side-effects elsewhere.
来源:https://stackoverflow.com/questions/61156893/displaying-figure-from-another-class-in-google-colab-using-matplotlib