Skip to content

Instantly share code, notes, and snippets.

@EckoTan0804
Last active March 2, 2021 20:22
Show Gist options
  • Save EckoTan0804/0d85cf1f74fa545ebaebb850b13c25f2 to your computer and use it in GitHub Desktop.
Save EckoTan0804/0d85cf1f74fa545ebaebb850b13c25f2 to your computer and use it in GitHub Desktop.
Save figure
import os
import matplotlib.pyplot as plt
def save_fig(
fig, fig_name, fig_dir, tight_layout=True, padding=False, fig_extension="png", resolution=300, transparent=True
):
"""
Save figure
Parameters
----------
fig : Matplotlib.figure.Figure
Figure to be saved
fig_name : str
Name of figure
fig_dir : str
Directory to save figure
tight_layout : bool, optional
Automatically adjusts subplot params so that the subplot(s) fits in to the figure area, by default True
padding: bool, optional
Paddings around figure, by default False
fig_extension : str, optional
Extension of figure, by default "png"
resolution : int, optional
The resolution in dots per inch, by default 300
transparent : bool, optional
Use transparent background, by default True
"""
if not os.path.exists(fig_dir):
os.makedirs(fig_dir)
path = os.path.join(fig_dir, fig_name + "." + fig_extension)
if tight_layout:
plt.tight_layout()
if not padding:
fig.savefig(
path, format=fig_extension, dpi=resolution, bbox_inches="tight", pad_inches=0, transparent=transparent
)
else:
fig.savefig(path, format=fig_extension, dpi=resolution, transparent=transparent)
print(f"Save {fig_name}.{fig_extension} in {fig_dir}")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment