[英]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.我实际上正在使用 google colaboratory 开展一个项目。 I'm using the pygad module(a Genetic Algorithm module).
我正在使用 pygad 模块(遗传算法模块)。 After running the algorithm, one can obtain the plot of a function, the fitness function, in such a way:
运行算法后,可以得到一个function的plot,适应度function,这样:
resultplot = ga_instance.plot_result()
Which returns the plot when executing the cell.执行单元格时返回 plot 。 However, the output of the function is
None
.但是,function 的 output 是
None
。 If I use the resultplot.savefig('plot.png')
function in this case I get an error.如果我在这种情况下使用
resultplot.savefig('plot.png')
function 会出现错误。
Is there another way of saving the image with a command?还有另一种使用命令保存图像的方法吗? Without having to use left click + save image as.
无需使用左键单击+将图像另存为。
Thanks!谢谢!
Thanks for using PyGAD .感谢您使用PyGAD 。
Unfortunately, the plot_result()
method does not return the created figure and thus you cannot save it.不幸的是,
plot_result()
方法不会返回创建的图形,因此您无法保存它。 But do not worry, you can still save the figure.不过不用担心,您仍然可以保存该图。
The plot_result()
simply plots the data saved in the best_solutions_fitness
attribute. plot_result()
只是绘制保存在best_solutions_fitness
属性中的数据。 This attribute can be accessed anywhere using the instance of the pygad.GA
class.可以使用
pygad.GA
class 的实例在任何地方访问此属性。
You can simply use the best_solutions_fitness
attribute to rebuild the figure and save it.您可以简单地使用
best_solutions_fitness
属性来重建图形并保存它。 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.无需调用
plot_result()
方法,只需使用创建图形的下一个代码,显示使用plot_result()
方法创建的相同 plot 并保存它。
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.如果您有任何其他问题,请告诉我。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.