Skip to content

Commit 20c6370

Browse files
0.29.0
svae_or_show_plot
1 parent d0e8cc1 commit 20c6370

2 files changed

Lines changed: 37 additions & 1 deletion

File tree

pyproject.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
77

88
[project]
99
name = "spotpython"
10-
version = "0.28.14"
10+
version = "0.29.0"
1111
authors = [
1212
{ name="T. Bartz-Beielstein", email="tbb@bartzundbartz.de" }
1313
]

src/spotpython/plot/utils.py

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
from matplotlib import pyplot as plt
2+
3+
4+
def save_or_show_plot(plt, filename=None) -> None:
5+
"""
6+
Save or show the plot based on the provided filename.
7+
8+
Args:
9+
plt (matplotlib.pyplot):
10+
The matplotlib pyplot object to save or show.
11+
filename (str, optional):
12+
The name of the file to save the plot. If None, the plot will be shown instead.
13+
Supported formats: 'pdf', 'png'.
14+
If a filename is provided, it must end with either '.pdf' or '.png'.
15+
If the filename is invalid, a ValueError will be raised.
16+
17+
Returns:
18+
None
19+
20+
Raises:
21+
ValueError: If the filename does not end with '.pdf' or '.png'.
22+
23+
Examples:
24+
>>> from spotpython.plot.utils import save_or_show_plot
25+
>>> save_or_show_plot("plot.pdf")
26+
>>> save_or_show_plot("plot.png")
27+
>>> save_or_show_plot() # This will show the plot
28+
"""
29+
# Save or show the plot
30+
if filename:
31+
if filename.endswith(".pdf") or filename.endswith(".png"):
32+
plt.savefig(filename, format=filename.split(".")[-1], bbox_inches="tight")
33+
else:
34+
raise ValueError("Filename must have a valid suffix: '.pdf' or '.png'.")
35+
else:
36+
plt.show()

0 commit comments

Comments
 (0)