aerosandbox.tools.pretty_plots ============================== .. py:module:: aerosandbox.tools.pretty_plots .. autoapi-nested-parse:: A set of tools used for making prettier Matplotlib plots. Submodules ---------- .. toctree:: :maxdepth: 1 /autoapi/aerosandbox/tools/pretty_plots/annotation/index /autoapi/aerosandbox/tools/pretty_plots/colors/index /autoapi/aerosandbox/tools/pretty_plots/formatting/index /autoapi/aerosandbox/tools/pretty_plots/labellines/index /autoapi/aerosandbox/tools/pretty_plots/plots/index /autoapi/aerosandbox/tools/pretty_plots/quickplot/index /autoapi/aerosandbox/tools/pretty_plots/threedim/index /autoapi/aerosandbox/tools/pretty_plots/utilities/index Attributes ---------- .. autoapisummary:: aerosandbox.tools.pretty_plots.x aerosandbox.tools.pretty_plots.data aerosandbox.tools.pretty_plots.palettes aerosandbox.tools.pretty_plots.preset_view_angles aerosandbox.tools.pretty_plots.t aerosandbox.tools.pretty_plots.x Functions --------- .. autoapisummary:: aerosandbox.tools.pretty_plots.eng_string aerosandbox.tools.pretty_plots.contour aerosandbox.tools.pretty_plots.pie aerosandbox.tools.pretty_plots.plot_color_by_value aerosandbox.tools.pretty_plots.plot_smooth aerosandbox.tools.pretty_plots.plot_with_bootstrapped_uncertainty aerosandbox.tools.pretty_plots.labelLines aerosandbox.tools.pretty_plots.ax_is_3d aerosandbox.tools.pretty_plots.show_plot aerosandbox.tools.pretty_plots.set_ticks aerosandbox.tools.pretty_plots.equal aerosandbox.tools.pretty_plots.get_discrete_colors_from_colormap aerosandbox.tools.pretty_plots.adjust_lightness aerosandbox.tools.pretty_plots.get_last_line_color aerosandbox.tools.pretty_plots.hline aerosandbox.tools.pretty_plots.vline aerosandbox.tools.pretty_plots.figure3d aerosandbox.tools.pretty_plots.ax_is_3d aerosandbox.tools.pretty_plots.set_preset_3d_view_angle aerosandbox.tools.pretty_plots.qp Package Contents ---------------- .. py:function:: eng_string(x, unit = '', format='%.3g', si=True, add_space_after_number = None) Taken from: https://stackoverflow.com/questions/17973278/python-decimal-engineering-notation-for-mili-10e-3-and-micro-10e-6/40691220 Returns float/int value formatted in a simplified engineering format - using an exponent that is a multiple of 3. :param x: The value to be formatted. Float or int. :param unit: A unit of the quantity to be expressed, given as a string. Example: Newtons -> "N" :param format: A printf-style string used to format the value before the exponent. :param si: if true, use SI suffix for exponent. (k instead of e3, n instead of e-9, etc.) 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" .. py:function:: 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) 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 :param X: If dataset is gridded, follow `contour` syntax. Otherwise, follow `tricontour` syntax. :param Y: If dataset is gridded, follow `contour` syntax. Otherwise, follow `tricontour` syntax. :param Z: If dataset is gridded, follow `contour` syntax. Otherwise, follow `tricontour` syntax. :param levels: See contour docs. :param colorbar: Should we draw a colorbar? :param linelabels: Should we add line labels? :param cmap: What colormap should we use? :param alpha: What transparency should all plot elements be? :param extend: See contour docs. :param linecolor: What color should the line labels be? :param linewidths: See contour docs. :param extendrect: See colorbar docs. :param linelabels_format: See ax.clabel docs. :param linelabels_fontsize: See ax.clabel docs. :param contour_kwargs: Additional keyword arguments for contour. :param contourf_kwargs: Additional keyword arguments for contourf. :param colorbar_kwargs: Additional keyword arguments for colorbar. :param linelabels_kwargs: Additional keyword arguments for the line labels (ax.clabel). :param \*\*kwargs: Additional keywords, which are passed to both contour and contourf. Returns: A tuple of (contour, contourf, colorbar) objects. .. py:data:: x .. py:function:: pie(values, names, colors = None, label_format = lambda name, value, percentage: name, sort_by = None, startangle = 0.0, center_text = None, x_labels = 1.25, y_max_labels = 1.3, arm_length=20, arm_radius=5) .. py:data:: data .. py:function:: 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. :param x: Array of x-points. :param y: Array of y-points. :param \*args: Args that will be passed into matplotlib.pyplot.plot(). Example: ".-" for a dotted line. :param c: Array of values that will map to colors. Must be the same length as x and y. :param cmap: The colormap to use. :param colorbar: Whether or not to display the colormap. [bool] :param colorbar_label: The label to add to the colorbar. Only applies if the colorbar is created. [str] :param clim: A tuple of (min, max) that assigns bounds to the colormap. Computed from the range of `c` if not given. :param \*\*kwargs: Kwargs that will be passed into matplotlib.pyplot.plot() Returns: .. py:function:: plot_smooth(*args, color=None, label=None, function_of = None, resample_resolution = 500, drop_nans = False, **kwargs) 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()`. :param \*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 :param color: Specifies the color of any line and/or markers that are plotted (as determined by the `fmt`). :param label: Attaches a label to this line. Use `plt.legend()` to display. :param resample_resolution: The number of points to use when resampling the interpolated curve. :param \*\*kwargs: Same keyword arguments as `matplotlib.pyplot.plot()`. Returns: A tuple `(x, y)` of the resampled points on the interpolated curve. Both `x` and `y` are 1D ndarrays. .. py:function:: 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: 0.8 * (1 - ci)**0.4, n_bootstraps=2000, n_fit_points=500, spline_degree=3, normalize = True, x_log_scale = False, y_log_scale = False) .. py:function:: labelLines(lines, align=True, xvals=None, drop_label=False, shrink_factor=0.05, yoffsets=0, outline_color='auto', outline_width=5, **kwargs) Label all lines with their respective legends. :param lines: The lines to label :type lines: list of matplotlib lines :param align: 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. :type align: boolean, optional :param xvals: The location of the labels. If a tuple, the labels will be evenly spaced between xfirst and xlast (in the axis units). :type xvals: (xfirst, xlast) or array of float, optional :param drop_label: If True, the label is consumed by the function so that subsequent calls to e.g. legend do not use it anymore. :type drop_label: bool, optional :param shrink_factor: Relative distance from the edges to place closest labels. Defaults to 0.05. :type shrink_factor: double, optional :param yoffsets: Distance relative to the line when positioning the labels. If given a number, the same value is used for all lines. :type yoffsets: number or list, optional. :param outline_color: Colour of the outline. If set to "auto", use the background color. If set to None, do not draw an outline. :type outline_color: None | "auto" | color :param outline_width: Width of the outline :type outline_width: number :param kwargs: Optional arguments passed to ax.text :type kwargs: dict, optional .. py:function:: ax_is_3d(ax = None) Determines if a Matplotlib axis object is 3D or not. :param ax: The axis object. If not given, uses the current active axes. Returns: A boolean of whether the axis is 3D or not. .. py:function:: show_plot(title = None, xlabel = None, ylabel = None, zlabel = None, dpi = None, savefig = None, savefig_transparent = False, tight_layout = True, tight_layout_pad = 0.25, 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) 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. :param title: 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. :param xlabel: If given, sets the xlabel of all axes. (Equivalent to `ax.set_xlabel(my_label)`) :param ylabel: If given, sets the ylabel of all axes. (Equivalent to `ax.set_ylabel(my_label)`) :param zlabel: If given, sets the zlabel of all axes, if the axis is 3D. (Equivalent to `ax.set_zlabel(my_label)`) :param dpi: If given, sets the dpi (display resolution, in Dots Per Inch) of the Figure. :param savefig: 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"]`) :param savefig_transparent: 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. :param tight_layout: If True, calls `plt.tight_layout()` to adjust the spacing of individual Axes. If False, skips this step. :param tight_layout_pad: If `tight_layout=True`, sets the padding width between the figure edge and the edges of the :param subplots: :param as a fraction of the font size. The default here is 0.25: :param which is well below the default of 1.08 in: :param matplotlib. This causes Matplotlib to waste less whitespace on padding.: :param legend: 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. :param legend_inline: 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). :param legend_frame: Boolean that controls whether a frame (rectangular background box) is displayed around the legend. Default is True. :param pretty_grids: Boolean that controls whether the gridlines are formatted have linewidths that are (subjectively) more readable. :param set_ticks: 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. :param show: 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. Returns: None (completely in-place function). If `show=True` (default), displays the plot after applying changes. .. py:function:: set_ticks(x_major = None, x_minor = None, y_major = None, y_minor = None, z_major = None, z_minor = None) .. py:function:: equal() Sets all axes to be equal. Works for both 2d plots and 3d plots. Returns: None .. py:data:: palettes .. py:function:: get_discrete_colors_from_colormap(cmap = 'rainbow', N = 8, lower_bound = 0, upper_bound = 1) 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. .. py:function:: adjust_lightness(color, amount=1.0) Converts a color to HLS space, then multiplies the lightness by `amount`, then converts back to RGB. :param color: A color, in any format that matplotlib understands. :param amount: The amount to multiply the lightness by. Valid range is 0 to infinity. Returns: A color, as an RGB tuple. .. py:function:: get_last_line_color() .. py:function:: hline(y, linestyle='--', color='k', text = None, text_xloc=0.5, text_ha='center', text_va='bottom', text_kwargs=None, **kwargs) .. py:function:: vline(x, linestyle='--', color='k', text = None, text_yloc=0.5, text_ha='right', text_va='center', text_kwargs=None, **kwargs) .. py:data:: preset_view_angles .. py:function:: figure3d(nrows = 1, ncols = 1, orthographic = True, box_aspect = None, adjust_colors = True, computed_zorder = True, ax_kwargs = None, **fig_kwargs) Creates a new 3D figure. Args and kwargs are passed into matplotlib.pyplot.figure(). Returns: (fig, ax) .. py:function:: ax_is_3d(ax = None) Determines if a Matplotlib axis object is 3D or not. :param ax: The axis object. If not given, uses the current active axes. Returns: A boolean of whether the axis is 3D or not. .. py:function:: set_preset_3d_view_angle(preset_view) .. py:data:: t .. py:function:: qp(*args, backend='plotly', show=True, plotly_renderer = 'browser', orthographic=True, stacklevel=1) Quickly plots ("QP") a 1D, 2D, or 3D dataset as a line plot with markers. Useful for exploratory data analysis. .. rubric:: Example >>> import aerosandbox.numpy as np >>> >>> x = np.linspace(0, 10) >>> y = x ** 2 >>> z = np.sin(x) >>> qp(x, y, z) :param \*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. :param backend: The backend to use. Current options: * "plotly" :param show: A boolean of whether or not to show the plot. :param plotly_renderer: 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. :param orthographic: A boolean of whether or not to use an orthographic (rather than persepctive) projection when viewing 3D plots. :param stacklevel: (Advanced) Choose the level of the stack that you want to retrieve plot labels at. Higher :param integers will get you higher: :type integers will get you higher: i.e., more end-user-facing :param argument in warnings.warn().: Returns: None (in-place) .. py:data:: x