aerosandbox.tools.pretty_plots#

A set of tools used for making prettier Matplotlib plots.

Subpackages#

Submodules#

Package Contents#

Functions#

eng_string(x[, unit, format, si, add_space_after_number])

Taken from: https://stackoverflow.com/questions/17973278/python-decimal-engineering-notation-for-mili-10e-3-and-micro-10e-6/40691220

contour(*args[, levels, colorbar, linelabels, cmap, ...])

An analogue for plt.contour and plt.tricontour and friends that produces a much prettier default graph.

pie(values, names[, colors, label_format, sort_by, ...])

plot_color_by_value(x, y, *args, c[, cmap, colorbar, ...])

Uses same syntax as matplotlib.pyplot.plot, except that c is now an array-like that maps to a specific color

plot_smooth(*args[, color, label, function_of, ...])

Plots a curve that interpolates a 2D dataset. Same as matplotlib.pyplot.plot(), with the following changes:

plot_with_bootstrapped_uncertainty(x, y[, ci, ...])

labelLines(lines[, align, xvals, drop_label, ...])

Label all lines with their respective legends.

ax_is_3d([ax])

Determines if a Matplotlib axis object is 3D or not.

show_plot([title, xlabel, ylabel, zlabel, dpi, ...])

Makes a matplotlib Figure (and all its constituent Axes) look "nice", then displays it.

set_ticks([x_major, x_minor, y_major, y_minor, ...])

equal()

Sets all axes to be equal. Works for both 2d plots and 3d plots.

get_discrete_colors_from_colormap([cmap, N, ...])

Returns uniformly-spaced discrete color samples from a (continuous) colormap.

adjust_lightness(color[, amount])

Converts a color to HLS space, then multiplies the lightness by amount, then converts back to RGB.

get_last_line_color()

hline(y[, linestyle, color, text, text_xloc, text_ha, ...])

vline(x[, linestyle, color, text, text_yloc, text_ha, ...])

figure3d([nrows, ncols, orthographic, box_aspect, ...])

Creates a new 3D figure. Args and kwargs are passed into matplotlib.pyplot.figure().

ax_is_3d([ax])

Determines if a Matplotlib axis object is 3D or not.

set_preset_3d_view_angle(preset_view)

qp(*args[, backend, show, plotly_renderer, ...])

Quickly plots ("QP") a 1D, 2D, or 3D dataset as a line plot with markers. Useful for exploratory data analysis.

Attributes#

aerosandbox.tools.pretty_plots.eng_string(x, unit='', format='%.3g', si=True, add_space_after_number=None)[source]#

Taken from: https://stackoverflow.com/questions/17973278/python-decimal-engineering-notation-for-mili-10e-3-and-micro-10e-6/40691220

Returns float/int value <x> formatted in a simplified engineering format - using an exponent that is a multiple of 3.

Parameters:
  • x (float) – The value to be formatted. Float or int.

  • unit (str) – A unit of the quantity to be expressed, given as a string. Example: Newtons -> “N”

  • format – A printf-style string used to format the value before the exponent.

  • si – if true, use SI suffix for exponent. (k instead of e3, n instead of e-9, etc.)

  • add_space_after_number (bool) –

Return type:

str

Examples:

With format=’%.2f’:
1.23e-08 -> 12.30e-9

123 -> 123.00

1230.0 -> 1.23e3

-1230000.0 -> -1.23e6

With si=True:

1230.0 -> “1.23k”

-1230000.0 -> “-1.23M”

With unit=”N” and si=True:

1230.0 -> “1.23 kN”

-1230000.0 -> “-1.23 MN”

aerosandbox.tools.pretty_plots.contour(*args, levels=31, colorbar=True, linelabels=True, cmap=None, alpha=0.7, extend='neither', linecolor='k', linewidths=0.5, extendrect=True, linelabels_format=eng_string, linelabels_fontsize=8, max_side_length_nondim=np.inf, colorbar_label=None, x_log_scale=False, y_log_scale=False, z_log_scale=False, mask=None, drop_nans=None, contour_kwargs=None, contourf_kwargs=None, colorbar_kwargs=None, linelabels_kwargs=None, **kwargs)[source]#

An analogue for plt.contour and plt.tricontour and friends that produces a much prettier default graph.

Can take inputs with either contour or tricontour syntax.

See syntax here:

https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.contour.html https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.contourf.html https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tricontour.html https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.tricontourf.html

Parameters:
  • X – If dataset is gridded, follow contour syntax. Otherwise, follow tricontour syntax.

  • Y – If dataset is gridded, follow contour syntax. Otherwise, follow tricontour syntax.

  • Z – If dataset is gridded, follow contour syntax. Otherwise, follow tricontour syntax.

  • levels (Union[int, List, numpy.ndarray]) – See contour docs.

  • colorbar (bool) – Should we draw a colorbar?

  • linelabels (bool) – Should we add line labels?

  • cmap – What colormap should we use?

  • alpha (float) – What transparency should all plot elements be?

  • extend (str) – See contour docs.

  • linecolor – What color should the line labels be?

  • linewidths (float) – See contour docs.

  • extendrect (bool) – See colorbar docs.

  • linelabels_format (Union[str, Callable[[float], str]]) – See ax.clabel docs.

  • linelabels_fontsize (float) – See ax.clabel docs.

  • contour_kwargs (Dict) – Additional keyword arguments for contour.

  • contourf_kwargs (Dict) – Additional keyword arguments for contourf.

  • colorbar_kwargs (Dict) – Additional keyword arguments for colorbar.

  • linelabels_kwargs (Dict) – Additional keyword arguments for the line labels (ax.clabel).

  • **kwargs – Additional keywords, which are passed to both contour and contourf.

  • max_side_length_nondim (float) –

  • colorbar_label (str) –

  • x_log_scale (bool) –

  • y_log_scale (bool) –

  • z_log_scale (bool) –

  • mask (numpy.ndarray) –

  • drop_nans (bool) –

Returns: A tuple of (contour, contourf, colorbar) objects.

aerosandbox.tools.pretty_plots.x[source]#
aerosandbox.tools.pretty_plots.pie(values, names, colors=None, label_format=lambda name, value, percentage: ..., sort_by=None, startangle=0.0, center_text=None, x_labels=1.25, y_max_labels=1.3, arm_length=20, arm_radius=5)#
Parameters:
  • values (Union[numpy.ndarray, List[float]]) –

  • names (List[str]) –

  • colors (Union[numpy.ndarray, List[str]]) –

  • label_format (Callable[[str, float, float], str]) –

  • sort_by (Union[numpy.ndarray, List[float], str, None]) –

  • startangle (float) –

  • center_text (str) –

  • x_labels (float) –

  • y_max_labels (float) –

aerosandbox.tools.pretty_plots.data[source]#
aerosandbox.tools.pretty_plots.plot_color_by_value(x, y, *args, c, cmap='turbo', colorbar=False, colorbar_label=None, clim=None, **kwargs)#

Uses same syntax as matplotlib.pyplot.plot, except that c is now an array-like that maps to a specific color pulled from cmap. Makes lines that are multicolored based on this c value.

Parameters:
  • x (numpy.ndarray) – Array of x-points.

  • y (numpy.ndarray) – Array of y-points.

  • *args – Args that will be passed into matplotlib.pyplot.plot(). Example: “.-” for a dotted line.

  • c (numpy.ndarray) – Array of values that will map to colors. Must be the same length as x and y.

  • cmap – The colormap to use.

  • colorbar (bool) – Whether or not to display the colormap. [bool]

  • colorbar_label (str) – The label to add to the colorbar. Only applies if the colorbar is created. [str]

  • clim (Tuple[float, float]) – A tuple of (min, max) that assigns bounds to the colormap. Computed from the range of c if not given.

  • **kwargs – Kwargs that will be passed into matplotlib.pyplot.plot()

Returns:

aerosandbox.tools.pretty_plots.plot_smooth(*args, color=None, label=None, function_of=None, resample_resolution=500, drop_nans=False, **kwargs)[source]#
Plots a curve that interpolates a 2D dataset. Same as matplotlib.pyplot.plot(), with the following changes:
  • uses B-splines to draw a smooth curve rather than a jagged polyline

  • By default, plots in line format fmt=’.-’ rather than fmt=’-’.

Other than that, almost all matplotlib.pyplot.plot() syntax can be used. See syntax here: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.plot.html

Example usage:
>>> import aerosandbox.numpy as np
>>>
>>> t = np.linspace(0, 1, 12)  # Parametric variable
>>> x = np.cos(2 * np.pi * t)
>>> y = np.cos(2 * np.pi * t ** 4) - t
>>>
>>> plot_smooth(
>>>     x, y, 'o--', color='purple'
>>> )
>>> plt.show()
  • Note: a true 2D interpolation is performed - it is not assumed y is a function of x, or vice versa. This can,

in rare cases, cause single-valuedness to not be preserved in cases where it logically should. If this is the case, you need to perform the interpolation yourself without plot_smooth().

Parameters:
  • *args

    Same arguments as matplotlib.pyplot.plot(). Notes on standard plot() syntax:

    Call signatures: >>> plot([x], y, [fmt], *, data=None, **kwargs) >>> plot([x], y, [fmt], [x2], y2, [fmt2], …, **kwargs)

    Examples: >>> plot(x, y) # plot x and y using default line style and color >>> plot(x, y, ‘bo’) # plot x and y using blue circle markers >>> plot(y) # plot y using x as index array 0..N-1 >>> plot(y, ‘r+’) # ditto, but with red plusses

  • color – Specifies the color of any line and/or markers that are plotted (as determined by the fmt).

  • label – Attaches a label to this line. Use plt.legend() to display.

  • resample_resolution (int) – The number of points to use when resampling the interpolated curve.

  • **kwargs – Same keyword arguments as matplotlib.pyplot.plot().

  • function_of (str) –

  • drop_nans (bool) –

Return type:

Tuple[aerosandbox.numpy.ndarray, aerosandbox.numpy.ndarray]

Returns: A tuple (x, y) of the resampled points on the interpolated curve. Both x and y are 1D ndarrays.

aerosandbox.tools.pretty_plots.plot_with_bootstrapped_uncertainty(x, y, ci=0.95, x_stdev=0.0, y_stdev=None, color=None, draw_data=True, label_line='Best Estimate', label_ci=True, label_data='Raw Data', line_alpha=0.9, ci_to_alpha_mapping=lambda ci: ..., n_bootstraps=2000, n_fit_points=500, spline_degree=3, normalize=True, x_log_scale=False, y_log_scale=False)[source]#
Parameters:
  • x (numpy.ndarray) –

  • y (numpy.ndarray) –

  • ci (Optional[Union[float, Iterable[float], numpy.ndarray]]) –

  • x_stdev (Union[None, float]) –

  • y_stdev (Union[None, float]) –

  • color (Optional[Union[str, Tuple[float]]]) –

  • draw_data (bool) –

  • label_line (Union[bool, str]) –

  • label_ci (bool) –

  • label_data (Union[bool, str]) –

  • line_alpha (float) –

  • ci_to_alpha_mapping (Callable[[float], float]) –

  • normalize (bool) –

  • x_log_scale (bool) –

  • y_log_scale (bool) –

aerosandbox.tools.pretty_plots.labelLines(lines, align=True, xvals=None, drop_label=False, shrink_factor=0.05, yoffsets=0, outline_color='auto', outline_width=5, **kwargs)[source]#

Label all lines with their respective legends.

Parameters:
  • lines (list of matplotlib lines) – The lines to label

  • align (boolean, optional) – If True, the label will be aligned with the slope of the line at the location of the label. If False, they will be horizontal.

  • xvals ((xfirst, xlast) or array of float, optional) – The location of the labels. If a tuple, the labels will be evenly spaced between xfirst and xlast (in the axis units).

  • drop_label (bool, optional) – If True, the label is consumed by the function so that subsequent calls to e.g. legend do not use it anymore.

  • shrink_factor (double, optional) – Relative distance from the edges to place closest labels. Defaults to 0.05.

  • yoffsets (number or list, optional.) – Distance relative to the line when positioning the labels. If given a number, the same value is used for all lines.

  • outline_color (None | "auto" | color) – Colour of the outline. If set to “auto”, use the background color. If set to None, do not draw an outline.

  • outline_width (number) – Width of the outline

  • kwargs (dict, optional) – Optional arguments passed to ax.text

aerosandbox.tools.pretty_plots.ax_is_3d(ax=None)[source]#

Determines if a Matplotlib axis object is 3D or not.

Parameters:

ax (matplotlib.axes.Axes) – The axis object. If not given, uses the current active axes.

Return type:

bool

Returns: A boolean of whether the axis is 3D or not.

aerosandbox.tools.pretty_plots.show_plot(title=None, xlabel=None, ylabel=None, zlabel=None, dpi=None, savefig=None, savefig_transparent=False, tight_layout=True, legend=None, legend_inline=False, legend_frame=True, pretty_grids=True, set_ticks=True, rotate_axis_labels=True, rotate_axis_labels_linewidth=14, show=True)[source]#

Makes a matplotlib Figure (and all its constituent Axes) look “nice”, then displays it.

Arguments control whether various changes (from the default matplotlib settings) are made to the plot.

One argument in particular, show (a boolean), controls whether the plot is displayed.

Parameters:
  • title (str) – If given, sets the title of the plot. If the Figure has multiple axes, this sets the Figure-level suptitle instead of setting the individual Axis title.

  • xlabel (str) – If given, sets the xlabel of all axes. (Equivalent to ax.set_xlabel(my_label))

  • ylabel (str) – If given, sets the ylabel of all axes. (Equivalent to ax.set_ylabel(my_label))

  • zlabel (str) – If given, sets the zlabel of all axes, if the axis is 3D. (Equivalent to ax.set_zlabel(my_label))

  • dpi (float) – If given, sets the dpi (display resolution, in Dots Per Inch) of the Figure.

  • savefig (Union[str, List[str]]) –

    If given, saves the figure to the given path(s).

    • If a string is given, saves the figure to that path.

      (E.g., savefig=”my_plot.png”)

    • If a list of strings is given, saves the figure to each of those paths.

      (E.g., savefig=[“my_plot.png”, “my_plot.pdf”])

  • savefig_transparent (bool) – If True, saves the figure with a transparent background. If False, saves the figure with a white background. Only has an effect if savefig is not None.

  • tight_layout (bool) – If True, calls plt.tight_layout() to adjust the spacing of individual Axes. If False, skips this step.

  • legend (bool) –

    This value can be True, False, or None.

    • If True, displays a legend on the current Axis.

    • If False, does not add a legend on the current Axis. (However, does not delete any existing legends.)

    • If None (default), goes through some logic to determine whether a legend should be displayed. If there

      is only one line on the current Axis, no legend is displayed. If there are multiple lines, a legend is ( in general) displayed.

  • legend_inline (bool) –

    Boolean that controls whether an “inline” legend is displayed.

    • If True, displays an “inline” legend, where the labels are next to the lines instead of in a box.

    • If False (default), displays a traditional legend.

    Only has an effect if legend=True (or legend=None, and logic determines that a legend should be displayed).

  • legend_frame (bool) – Boolean that controls whether a frame (rectangular background box) is displayed around the legend. Default is True.

  • pretty_grids (bool) – Boolean that controls whether the gridlines are formatted have linewidths that are (subjectively) more readable.

  • set_ticks (bool) –

    Boolean that controls whether the tick and grid locations + labels are formatted to be ( subjectively) more readable.

    Works with both linear and log scales, and with both 2D and 3D plots.

  • show (bool) – Boolean that controls whether the plot is displayed after all plot changes are applied. Default is True. You may want to set this to False if you want to make additional manual changes to the plot before displaying it. Default is True.

  • rotate_axis_labels (bool) –

  • rotate_axis_labels_linewidth (int) –

Returns: None (completely in-place function). If show=True (default), displays the plot after applying changes.

aerosandbox.tools.pretty_plots.set_ticks(x_major=None, x_minor=None, y_major=None, y_minor=None, z_major=None, z_minor=None)[source]#
Parameters:
  • x_major (Union[float, int]) –

  • x_minor (Union[float, int]) –

  • y_major (Union[float, int]) –

  • y_minor (Union[float, int]) –

  • z_major (Union[float, int]) –

  • z_minor (Union[float, int]) –

aerosandbox.tools.pretty_plots.equal()[source]#

Sets all axes to be equal. Works for both 2d plots and 3d plots.

Returns: None

Return type:

None

aerosandbox.tools.pretty_plots.palettes[source]#
aerosandbox.tools.pretty_plots.get_discrete_colors_from_colormap(cmap='rainbow', N=8, lower_bound=0, upper_bound=1)[source]#

Returns uniformly-spaced discrete color samples from a (continuous) colormap. :param cmap: Name of a colormap. :param N: Number of colors to retrieve from colormap.

Returns: A Nx4 array of (R, G, B, A) colors.

Parameters:
  • cmap (str) –

  • N (int) –

  • lower_bound (float) –

  • upper_bound (float) –

aerosandbox.tools.pretty_plots.adjust_lightness(color, amount=1.0)[source]#

Converts a color to HLS space, then multiplies the lightness by amount, then converts back to RGB.

Parameters:
  • color – A color, in any format that matplotlib understands.

  • amount – The amount to multiply the lightness by. Valid range is 0 to infinity.

Returns: A color, as an RGB tuple.

aerosandbox.tools.pretty_plots.get_last_line_color()[source]#
aerosandbox.tools.pretty_plots.hline(y, linestyle='--', color='k', text=None, text_xloc=0.5, text_ha='center', text_va='bottom', text_kwargs=None, **kwargs)[source]#
Parameters:

text (str) –

aerosandbox.tools.pretty_plots.vline(x, linestyle='--', color='k', text=None, text_yloc=0.5, text_ha='right', text_va='center', text_kwargs=None, **kwargs)[source]#
Parameters:

text (str) –

aerosandbox.tools.pretty_plots.preset_view_angles[source]#
aerosandbox.tools.pretty_plots.figure3d(nrows=1, ncols=1, orthographic=True, box_aspect=None, adjust_colors=True, computed_zorder=True, ax_kwargs=None, **fig_kwargs)[source]#

Creates a new 3D figure. Args and kwargs are passed into matplotlib.pyplot.figure().

Returns: (fig, ax)

Parameters:
  • nrows (int) –

  • ncols (int) –

  • orthographic (bool) –

  • box_aspect (Tuple[float]) –

  • adjust_colors (bool) –

  • computed_zorder (bool) –

  • ax_kwargs (Dict) –

Return type:

Tuple[matplotlib.figure.Figure, mpl_toolkits.mplot3d.axes3d.Axes3D]

aerosandbox.tools.pretty_plots.ax_is_3d(ax=None)[source]#

Determines if a Matplotlib axis object is 3D or not.

Parameters:

ax (matplotlib.axes.Axes) – The axis object. If not given, uses the current active axes.

Return type:

bool

Returns: A boolean of whether the axis is 3D or not.

aerosandbox.tools.pretty_plots.set_preset_3d_view_angle(preset_view)[source]#
Parameters:

preset_view (str) –

Return type:

None

aerosandbox.tools.pretty_plots.t[source]#
aerosandbox.tools.pretty_plots.qp(*args, backend='plotly', show=True, plotly_renderer='browser', orthographic=True, stacklevel=1)[source]#

Quickly plots (“QP”) a 1D, 2D, or 3D dataset as a line plot with markers. Useful for exploratory data analysis.

Example

>>> import aerosandbox.numpy as np
>>>
>>> x = np.linspace(0, 10)
>>> y = x ** 2
>>> z = np.sin(x)
>>> qp(x, y, z)
Parameters:
  • *args – The arguments that you want to plot. You can provide 1, 2, or 3 arrays, all of which should be 1D and of the same length.

  • backend – The backend to use. Current options: * “plotly”

  • show – A boolean of whether or not to show the plot.

  • plotly_renderer (Union[str, None]) – A string of what to use as the Plotly renderer. If you don’t want to overwrite a default that you’ve already set, set this variable to None.

  • orthographic – A boolean of whether or not to use an orthographic (rather than persepctive) projection when viewing 3D plots.

  • stacklevel – (Advanced) Choose the level of the stack that you want to retrieve plot labels at. Higher

  • higher (integers will get you) –

  • warnings.warn(). (argument in) –

Return type:

None

Returns: None (in-place)

aerosandbox.tools.pretty_plots.x[source]#