Skip to content

Commit ccfe679

Browse files
committed
Update pygad.py
Allows to save the plot into a file as an option, since linux might throw an error showing it.
1 parent dd7a670 commit ccfe679

File tree

1 file changed

+8
-2
lines changed

1 file changed

+8
-2
lines changed

pygad.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -2530,7 +2530,7 @@ def best_solution(self, pop_fitness=None):
25302530

25312531
return best_solution, best_solution_fitness, best_match_idx
25322532

2533-
def plot_result(self, title="PyGAD - Iteration vs. Fitness", xlabel="Generation", ylabel="Fitness", linewidth=3):
2533+
def plot_result(self, title="PyGAD - Iteration vs. Fitness", xlabel="Generation", ylabel="Fitness", linewidth=3, save_as=None):
25342534

25352535
"""
25362536
Creates and shows a plot that summarizes how the fitness value evolved by generation. Can only be called after completing at least 1 generation. If no generation is completed, an exception is raised.
@@ -2540,6 +2540,7 @@ def plot_result(self, title="PyGAD - Iteration vs. Fitness", xlabel="Generation"
25402540
xlabel: Label on the X-axis.
25412541
ylabel: Label on the Y-axis.
25422542
linewidth: Line width of the plot.
2543+
save_as: save image instead of showing it.
25432544
25442545
Returns the figure.
25452546
"""
@@ -2555,7 +2556,12 @@ def plot_result(self, title="PyGAD - Iteration vs. Fitness", xlabel="Generation"
25552556
matplotlib.pyplot.title(title)
25562557
matplotlib.pyplot.xlabel(xlabel)
25572558
matplotlib.pyplot.ylabel(ylabel)
2558-
matplotlib.pyplot.show()
2559+
2560+
if save_as is None:
2561+
matplotlib.pyplot.show() # show plot
2562+
else:
2563+
fig.savefig(f'{save_as}.png') # save as image
2564+
25592565
return fig
25602566

25612567
def save(self, filename):

0 commit comments

Comments
 (0)