如何保存作为 jupyter 中函数输出的 matplotlib 图?

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

我实际上正在使用 google colaboratory 开展一个项目。我正在使用 pygad 模块(遗传算法模块)。 运行算法后,可以得到一个函数的图,即适应度函数,这样:

resultplot = ga_instance.plot_result()

其中returns执行单元格时的情节。然而,函数的输出是None。如果我在这种情况下使用 resultplot.savefig('plot.png') 函数,则会出现错误。

还有其他方法可以用命令保存图片吗?无需使用左键单击 + 将图像另存为。

谢谢!

感谢使用 PyGAD

很遗憾,plot_result() 方法没有return 创建的图形,因此您无法保存它。不过别着急,身材还是可以保存的。

plot_result() 简单地绘制保存在 best_solutions_fitness 属性中的数据。可以使用 pygad.GA class.

的实例在任何地方访问此属性

您可以简单地使用best_solutions_fitness 属性重建图形并保存。这是你应该做的:

无需调用 plot_result() 方法,只需使用下一个创建图形的代码,显示使用 plot_result() 方法创建的相同图并保存它。

import matplotlib.pyplot

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

如果您有任何其他问题,请告诉我。

再次感谢您使用PyGAD :)