From e30eb70e708675d6189d0bf0298d4a3ac6cc4634 Mon Sep 17 00:00:00 2001 From: Alasdair Gray Date: Thu, 8 Jun 2023 21:41:17 -0400 Subject: [PATCH 1/4] Add helper function for saving figure in multiple formats --- niceplots/utils.py | 70 ++++++++++++++++++++++++++++++++++++++++------ 1 file changed, 62 insertions(+), 8 deletions(-) diff --git a/niceplots/utils.py b/niceplots/utils.py index caa3271..6ce66d6 100644 --- a/niceplots/utils.py +++ b/niceplots/utils.py @@ -180,7 +180,6 @@ def draggable_legend(axis=None, color_on=True, **kwargs): # Loop over each line in the plot and create a label for idx, line in enumerate(axis.lines): - # Set the starting coordinates of the label coords[0] = xs[idx] coords[1] = ys[idx] @@ -316,7 +315,6 @@ def horiz_bar(labels, times, header, nd=1, size=[5, 0.5], color=None): # Actual loop that draws each bar for j, (l, t, ax) in enumerate(zip(labels, times, axarr)): - # Draw the gray line and singular yellow dot ax.axhline(y=1, c=line_color, lw=3, zorder=0, alpha=0.5) ax.scatter([t], [1], c=color, lw=0, s=100, zorder=1, clip_on=False) @@ -342,7 +340,12 @@ def horiz_bar(labels, times, header, nd=1, size=[5, 0.5], color=None): ax.set_ylabel(l, rotation="horizontal", ha="right", va="center") string = "{number:.{digits}f}".format(number=t, digits=nd) ax.annotate( - string, xy=(1, 1), xytext=(6, 0), xycoords=ax.get_yaxis_transform(), textcoords="offset points", va="center" + string, + xy=(1, 1), + xytext=(6, 0), + xycoords=ax.get_yaxis_transform(), + textcoords="offset points", + va="center", ) # Create the top bar line @@ -368,7 +371,6 @@ def stacked_plots( xlim=None, dpi=200, ): - # If it's a dictionary, make it into a list so we can generically loop over it if isinstance(data_dict_list, dict): data_dict_list = [data_dict_list] @@ -541,7 +543,10 @@ def plot_opt_prob( nColor = len(colors) # --- Create grid of points for evaluating functions --- - X, Y = np.meshgrid(np.linspace(xRange[0], xRange[1], nPoints), np.linspace(yRange[0], yRange[1], nPoints)) + X, Y = np.meshgrid( + np.linspace(xRange[0], xRange[1], nPoints), + np.linspace(yRange[0], yRange[1], nPoints), + ) # --- Evaluate objective and constraint functions --- Fobj = obj(X, Y) @@ -567,9 +572,19 @@ def plot_opt_prob( for conValue in g: contour = ax.contour(X, Y, conValue, levels=[0.0], colors=colors[colorIndex % nColor]) if conStyle.lower() == "hashed": - plt.setp(contour.collections, path_effects=[patheffects.withTickedStroke(angle=60, length=2)]) + plt.setp( + contour.collections, + path_effects=[patheffects.withTickedStroke(angle=60, length=2)], + ) elif conStyle.lower() == "shaded": - ax.contourf(X, Y, conValue, levels=[0.0, np.inf], colors=colors[colorIndex % nColor], alpha=0.4) + ax.contourf( + X, + Y, + conValue, + levels=[0.0, np.inf], + colors=colors[colorIndex % nColor], + alpha=0.4, + ) colorIndex += 1 @@ -600,7 +615,17 @@ def plot_opt_prob( def plot_colored_line( - x, y, c, cmap=None, fig=None, ax=None, addColorBar=False, cRange=None, cBarLabel=None, norm=None, **kwargs + x, + y, + c, + cmap=None, + fig=None, + ax=None, + addColorBar=False, + cRange=None, + cBarLabel=None, + norm=None, + **kwargs, ): """Plot an XY line whose color is determined by some other variable C @@ -865,6 +890,35 @@ def plot_nested_pie( return pieObjects +def save_figs(fig, name, formats, **kwargs): + """Save a figure in multiple formats + + Parameters + ---------- + fig : Matplotlib figure + The figure to save + name : str + Output path for the files, e.g "path/to/file/file_name", no file extension required + formats : str, list[str] + file formats to save the figure in, e.g. "png", "pdf", "svg" + kwargs : + Any keyword arguments to pass to `plt.savefig()` + """ + + # --- Strip any extension from the name --- + fileName = os.path.splitext(name)[0] + + # --- Convert the file format to a list if only one given --- + if not hasattr(formats, "__iter__"): + formats = [formats] + + # --- Save the figures --- + for ext in formats: + if ext[0] == ".": + ext = ext[1:] + plt.savefig(fileName + "." + ext, **kwargs) + + def All(): """Runs commonly called functions provided in this module.""" adjust_spines() From 7c5e6bfab3a62c807a09d63234bfa5f7144b731a Mon Sep 17 00:00:00 2001 From: Alasdair Gray Date: Wed, 14 Feb 2024 09:16:26 -0500 Subject: [PATCH 2/4] Fix behaviour of `save_figs` when single format string passed --- niceplots/styles/doumont-light.mplstyle | 58 ++++++++++++------------- niceplots/utils.py | 2 +- 2 files changed, 30 insertions(+), 30 deletions(-) diff --git a/niceplots/styles/doumont-light.mplstyle b/niceplots/styles/doumont-light.mplstyle index 34daa08..0c06757 100644 --- a/niceplots/styles/doumont-light.mplstyle +++ b/niceplots/styles/doumont-light.mplstyle @@ -1,50 +1,50 @@ # Figure settings -savefig.dpi : 600 -figure.constrained_layout.use : True +savefig.dpi: 600 +figure.constrained_layout.use: True # Axes settings -axes.spines.top : False -axes.spines.right : False -axes.labelpad : 8.0 -axes.xmargin : 0 -axes.ymargin : 0 +axes.spines.top: False +axes.spines.right: False +axes.labelpad: 8.0 +axes.xmargin: 0 +axes.ymargin: 0 # Font settings -font.family : sans-serif -font.sans-serif : CMU Bright -axes.unicode_minus : False -font.size : 18 +font.family: sans-serif +font.sans-serif: CMU Bright +axes.unicode_minus: False +font.size: 18 -axes.labelweight : bold +axes.labelweight: bold -xtick.labelsize : small -ytick.labelsize : small +xtick.labelsize: small +ytick.labelsize: small -text.latex.preamble : r"\usepackage{cmbright}" +text.latex.preamble: r"\usepackage{cmbright}" mathtext.default: regular -pgf.rcfonts : True +pgf.rcfonts: True # Legend settings -legend.columnspacing : 0.2 -legend.frameon : False +legend.columnspacing: 1.0 +legend.frameon: False # Line settings -lines.linewidth : 2.0 -lines.markeredgewidth : 1.0 +lines.linewidth: 2.0 +lines.markeredgewidth: 1.0 # Color settings -axes.prop_cycle : cycler('color', ['e29400ff', '1E90FF', 'E21A1A', '00a650ff', '800000ff', 'ff8f00', '800080ff', '00A6D6', '000000ff']) +axes.prop_cycle: cycler('color', ['e29400ff', '1E90FF', 'E21A1A', '00a650ff', '800000ff', 'ff8f00', '800080ff', '00A6D6', '000000ff']) # Use this parameter, which (hopefully) nobody will ever use, to store text the names of the colors in the color cycle -keymap.help : Yellow, Blue, Red, Green, Maroon, Orange, Purple, Cyan, Black - -lines.markeredgecolor : w -axes.edgecolor : 5a5758ff -text.color : 5a5758ff -axes.labelcolor : 5a5758ff -xtick.color : 5a5758ff -ytick.color : 5a5758ff +keymap.help: Yellow, Blue, Red, Green, Maroon, Orange, Purple, Cyan, Black + +lines.markeredgecolor: w +axes.edgecolor: 5a5758ff +text.color: 5a5758ff +axes.labelcolor: 5a5758ff +xtick.color: 5a5758ff +ytick.color: 5a5758ff diff --git a/niceplots/utils.py b/niceplots/utils.py index 7794675..372cfb3 100644 --- a/niceplots/utils.py +++ b/niceplots/utils.py @@ -1036,7 +1036,7 @@ def save_figs(fig, name, formats, format_kwargs=None, **kwargs): fileName = os.path.splitext(name)[0] # --- Convert the file format to a list if only one given --- - if not isinstance(formats, Iterable): + if not isinstance(formats, Iterable) or isinstance(formats, str): formats = [formats] # --- Save the figures --- From 20cb0181332f5b6f7c50dd34b6701f29b62a271c Mon Sep 17 00:00:00 2001 From: Alasdair Gray Date: Wed, 14 Feb 2024 09:29:49 -0500 Subject: [PATCH 3/4] Make check simpler --- niceplots/utils.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/niceplots/utils.py b/niceplots/utils.py index 372cfb3..885b960 100644 --- a/niceplots/utils.py +++ b/niceplots/utils.py @@ -1036,7 +1036,7 @@ def save_figs(fig, name, formats, format_kwargs=None, **kwargs): fileName = os.path.splitext(name)[0] # --- Convert the file format to a list if only one given --- - if not isinstance(formats, Iterable) or isinstance(formats, str): + if isinstance(formats, str): formats = [formats] # --- Save the figures --- From f0d2b2912b5b276c0cdc1176ef220b880a977d51 Mon Sep 17 00:00:00 2001 From: Alasdair Gray Date: Wed, 14 Feb 2024 09:33:43 -0500 Subject: [PATCH 4/4] flake8 fix --- niceplots/utils.py | 1 - 1 file changed, 1 deletion(-) diff --git a/niceplots/utils.py b/niceplots/utils.py index 885b960..86b0ba5 100644 --- a/niceplots/utils.py +++ b/niceplots/utils.py @@ -10,7 +10,6 @@ import warnings import os import copy -from collections.abc import Iterable from collections import OrderedDict # ==============================================================================