def export(fig: plt.Figure,
           filename: Union[AnyStr, os.fspath],
           target_dir: Union[AnyStr, os.fspath] = "plots/",
           file_formats: Tuple[str, ...] = (".pdf", ".png"),
           save_as_tikz: bool = False,
           close_figure: bool = False) -> None:
    """
    Convenience function for saving a matplotlib figure.

    :param fig: A matplotlib figure.
    :param filename: Filename of the plot without .pdf suffix.
    :param file_formats: Tuple of file formats specifying the format
                         figure will be saved as.
    :param target_dir: Directory where the plot will be saved in.
                       Default is './plots/'.
    :param save_as_tikz: Save the plot also as raw tikz tex document.
    :param close_figure: Whether to close the figure after saving it.
                         Default is False
    :return: None
    """
    os.makedirs(target_dir, exist_ok=True)

    for file_format in file_formats:
        fig.savefig(os.path.join(target_dir, f"{filename}{file_format}"),
                    bbox_inches="tight")

    if save_as_tikz:
        save_figure_as_tikz_tex_file(fig=fig,
                                     target_path=os.path.join(
                                         target_dir, f"{filename}_tikz.tex"))

    if close_figure:
        plt.close(fig)
        fig.clf()
def save_fig_or_show(save_fig: bool = True,
                     figure_path: str = None,
                     fig: plt.Figure = None):
    """
    Save figure or show figure
    """

    if save_fig:
        if fig is None:
            plt.savefig(figure_path, bbox_inches='tight')
            plt.clf()
        else:
            fig.savefig(figure_path, bbox_inches='tight')
            fig.clf()
    else:
        plt.show()
Exemple #3
0
def save_plot(fig: plt.Figure, filename: str) -> None:
    fig.savefig(filename)
    fig.clf()
    plt.close()