Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
117 views
in Technique[技术] by (71.8m points)

python - How can I save a matplotlib plot that is the output of a function in jupyter?

I'm actually working on a project using google colaboratory. I'm using the pygad module(a Genetic Algorithm module). After running the algorithm, one can obtain the plot of a function, the fitness function, in such a way:

resultplot = ga_instance.plot_result()

Which returns the plot when executing the cell. However, the output of the function is None. If I use the resultplot.savefig('plot.png') function in this case I get an error.

Is there another way of saving the image with a command? Without having to use left click + save image as.

Thanks!

question from:https://stackoverflow.com/questions/66055330/how-can-i-save-a-matplotlib-plot-that-is-the-output-of-a-function-in-jupyter

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Thanks for using PyGAD.

Unfortunately, the plot_result() method does not return the created figure and thus you cannot save it. But do not worry, you can still save the figure.

The plot_result() simply plots the data saved in the best_solutions_fitness attribute. This attribute can be accessed anywhere using the instance of the pygad.GA class.

You can simply use the best_solutions_fitness attribute to rebuild the figure and save it. Here is what you should do:

Rather than calling the plot_result() method, simply use the next code which creates the figure, shows the same plot created using the plot_result() method, and saves it.

import matplotlib.pyplot

matplotlib.pyplot.figure()
matplotlib.pyplot.plot(ga_instance.best_solutions_fitness)
matplotlib.pyplot.savefig("PyGAD_figure.jpg")
matplotlib.pyplot.show()

Please let me know if you have any other questions.

Again, thanks for using PyGAD :)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...