API

NicePlots: A collection of stylesheets and helper functions for matplotlib

niceplots.utils.All()[source]

Runs commonly called functions provided in this module.

niceplots.utils.adjust_spines(ax=None, spines=['left', 'bottom'], outward=True)[source]

Function to shift the axes/spines so they have that offset Doumont look.

niceplots.utils.draggable_legend(axis=None, color_on=True, **kwargs)[source]

Function to create draggable labels on a plot.

niceplots.utils.get_available_styles()[source]

Get a list of the names of styles available.

Returns:
list

The names of the available styles.

niceplots.utils.get_colors(styleName=None)[source]

Get a dictionary with the colors for the current style. This function only works when niceplots styles are used (not built-in matplotlib ones).

Parameters:
styleNamestr, optional

Name of desired style. By default gets the colors for the current style. Avaiable styles are:

  • doumont-light: the niceplots style you know and love

  • doumont-dark: the dark version of the niceplots style you know and love

  • james-dark: a really cool alternative to classic niceplots

  • james-light: a version of james with a light background, naturally

Returns:
dict

Dictionary of the colors for the requested style. The keys are human-readable names and the keys are the hex codes. It also adds color names from the rcParams that are generally useful:

  • “Axis”: axis spine color

  • “Background” axis background color

  • “Text”: default text color

  • “Label”: axis label color

niceplots.utils.get_colors_list(styleName=None)[source]

Get a list with the colors for the current style. This function works with all matplotlib styles.

Parameters:
styleNamestr, optional

Name of desired style. By default gets the colors for the current style. Avaiable styles are:

  • doumont-light: the niceplots style you know and love

  • doumont-dark: the dark version of the niceplots style you know and love

  • james-dark: a really cool alternative to classic niceplots

  • james-light: a version of james with a light background, naturally

Returns:
list

List of the colors for the requested style.

niceplots.utils.get_style(styleName='doumont-light')[source]

Get the stylesheet to pass to matplotlib’s style setting functions. This function works both with niceplots styles and matplotlib’s built-in styles. Usage examples:

import matplotlib.pyplot as plt
import niceplots

plt.style.use(niceplots.get_style())
plt.plot([0, 1], [0, 1])

# Or you can use it within a context manager
with plt.style.context(niceplots.get_style()):
    plt.plot([0, 1], [0, 1])

# Also try different styles
plt.style.use(niceplots.get_style("james-dark"))  # niceplots james dark style
plt.style.use(niceplots.get_style("default"))  # matplotlib default style
Parameters:
styleNamestr, optional

Name of desired style. By default uses doumont-light style. Avaiable styles are:

  • doumont-light: the niceplots style you know and love

  • doumont-dark: the dark version of the niceplots style you know and love

  • james-dark: a really cool alternative to classic niceplots

  • james-light: a version of james with a light background, naturally

Returns:
str

The style string to be passed to one of matplotlib’s style setting functions.

niceplots.utils.handle_close(evt)[source]

Handler function that saves the figure as a pdf if the window is closed.

niceplots.utils.horiz_bar(labels, times, header, nd=1, size=[5, 0.5], color=None)[source]

Creates a horizontal bar chart to compare positive numbers.

Parameters:
labelslist of str

contains the ordered labels for each data set

timeslist of float

contains the numerical data for each entry

headerlist of two str

contains the left and right header for the labels and numeric data, respectively

ndfloat

the number of digits to show after the decimal point for the data

sizelist of two float

the size of the final figure (iffy results)

colorstr

hexcode for the color of the scatter points used

Returns:
fig: matplotlib Figure

Figure created

axes: array of matplotlib Axes

The subplot axes, one for each bar

niceplots.utils.label_line_ends(ax, lines=None, labels=None, colors=None, x_offset_pts=6, y_offset_pts=0, **kwargs)[source]

Place a label just to the right of each line in the axes

Note: Because the labels are placed outside of the axes, this function works best for plots where all lines end as close to the right edge of the axes as possible. Additionally you need to either use constrained_layout=True (as NicePlots styles do), or call plt.tight_layout() after calling this function.

Parameters:
axMatplotlib axes

axes to label the lines of

linesiterable of matplotlib line objects, optional

Lines to label, by default all lines in the axes

labelslist of strings, optional

Labels for each line, by default uses each line’s label attribute

colorssingle or list of colors, optional

Color(s) to use for each line, can be a single color for all lines or a list containing an entry for each line, by default uses each line’s color

x_offset_ptsint, float, optional

Horizontal offset of label from the right end of the line, in points, by default 6

y_offset_ptsint, float, optional

Vertical offset of label from the right end of the line, in points, by default 0

kwargs

Any valid keywords for matplotlib’s annotate function, except xy, xytext, color, textcoords, va

Returns:
list of matplotlib annotation objects

The annotations created

niceplots.utils.plot_colored_line(x, y, c, cmap=None, fig=None, ax=None, addColorBar=False, cRange=None, cBarLabel=None, norm=None, **kwargs)[source]

Plot an XY line whose color is determined by some other variable C

Parameters:
xiterable of length n

x data

yiterable of length n

y data

citerable of length n

Data for linecolor

cmapstr or matplotlib colormap, optional

Colormap to use for the objective contours, by default will use nicePlots’ parula map

figmatplotlib figure object, optional

figure to plot on, by default None, in which case a new figure will be created and returned by the function

axmatplotlib axes object, optional

axes to plot on, by default None, in which case a new figure will be created and returned by the function

addColorBarbool, optional

Whether to add a colorbar to the axes, by default False

cRangeiterable of length 2, optional

Upper and lower limit for the colormap, by default None, in which case the min and max values of c are used.

cBarLabelstr, optional

Label for the colormap, by default None

normmatplotlib.colors.Normalize, optional

Specify colormap mapping; both this and cRange cannot be specified, it must be one or the other (or neither)

Returns:
figmatplotlib figure object

Figure containing the plot. Returned only if no input ax object is specified

axmatplotlib axes object

Axis with the colored line. Returned only if no input ax object is specified

niceplots.utils.plot_nested_pie(data, colors=None, alphas=None, ax=None, innerKwargs=None, outerKwargs=None)[source]

Create a two-level pie chart where the inner pie chart is a sum of related categories from the outer one. The labels are by default set to the keys in the data dictionary.

Parameters:
datanested dict

Data to plot. Formatted as:

{
    "Category 1": {
        "Subcategory 1": 0.5,
        "Subcategory 2": 1.5,
    },
    "Category 2": {
        "Subcategory 1": 2.5,
    },
    ...
}
colorsstr or list of str with hex colors, optional

Colors to use for the inner wedges. Can either specify a qualitative matplotlib colormap (it will assume this is the case if a string is specified), or a list of colors specified with hex codes (e.g., “#F4A103”), by default will use nice colors (niceplots default). Loops through the colors if more categories than colors are specified.

alphasiterable of floats at least as long as the max number of subcategories for a given category

Transparencies to use to vary the color in the outer categories

axmatplotlib axes object, optional

axes to plot on, by default None, in which case a new figure will be created and returned by the function

innerKwargsdict

Dictionary of keyword arguments to pass to matplotlib.pyplot.pie for the inner pie chart. “color” and “radius” are important ones for the nested pie chart and I recommend not touching those unless you know what you’re doing. labels, rotatelabels, wedgeprops, and textprops are also all set by default in this function, but can be overridden using this parameter

outerKwargsdict

Dictionary of keyword arguments to pass to matplotlib.pyplot.pie for the outer pie chart. “color” and “radius” are important ones for the nested pie chart and I recommend not touching those unless you know what you’re doing. labels, rotatelabels, wedgeprops, and textprops are also all set by default in this function, but can be overridden using this parameter

Returns:
pieObjectsdict of matplotlib.patches.Wedge and matplotlib Text objects

Wedges and text objects for the pie plot, formatted similarly to the input data dict:

{
    "Category 1": {
        "wedge": Category 1 wedge
        "text": Category 1 text
        "Subcategory 1": {"wedge": Subcategory 1 wedge, "text": Subcategory 1 wedge},
        "Subcategory 2": {"wedge": Subcategory 2 wedge, "text": Subcategory 2 wedge},
    },
    "Category 2": {
        "wedge": Category 2 wedge
        "text": Category 2 text
        "Subcategory 1": {"wedge": Subcategory 1 wedge, "text": Subcategory 1 wedge},
    },
    ...
}
figmatplotlib figure object

Figure containing the plot. Returned only if no input ax object is specified

axmatplotlib axes object

Axis with the colored line. Returned only if no input ax object is specified

niceplots.utils.plot_opt_prob(obj, xRange, yRange, ineqCon=None, eqCon=None, nPoints=51, optPoint=None, conStyle='shaded', ax=None, colors=None, cmap=None, levels=None, labelAxes=True)[source]

Generate a contour plot of a 2D constrained optimisation problem

Parameters:
objfunction

Objective function, should accept inputs in the form f = obj(x, y) where x and y are 2D arrays

xRangelist or array

Upper and lower limits of the plot in x

yRangelist or array

Upper and lower limits of the plot in y

ineqConfunction or list of functions, optional

Inequality constraint functions, should accept inputs in the form g = g(x, y) where x and y are 2D arrays. Constraints are assumed to be of the form g <= 0

eqConfunctions or list of functions, optional

Equality constraint functions, should accept inputs in the form h = h(x, y) where x and y are 2D arrays. Constraints are assumed to be of the form h == 0

nPointsint, optional

Number of points in each direction to evaluate the objective and constraint functions at

optPointlist or array, optional

Optimal Point, if you want to plot a point there, by default None

conStylestr, optional

Controls how inequality constraints are represented, “shaded” will shade the infeasible regions while “hashed” will place hashed lines on the infeasible side of the feasible boundary, by default “shaded”, note the “hashed” option only works for matplotlib >= 3.4

axmatplotlib axes object, optional

axes to plot, by default None, in which case a new figure will be created and returned by the function

colorslist, optional

List of colors to use for the constraint lines, by default uses the current matplotlib color cycle

cmapcolormap, optional

Colormap to use for the objective contours, by default will use nicePlots’ parula map

levelslist, array, int, optional

Number or values of contour lines to plot for the objective function

labelAxesbool, optional

Whether to label the x and y axes, by default True, in which case the axes will be labelled, “$X_1$” and “$X_2$”

Returns:
figmatplotlib figure object

Figure containing the plot. Returned only if no input ax object is specified

axmatplotlib axes object, but only if no ax object is specified

Axis with the colored line. Returned only if no input ax object is specified

niceplots.utils.plot_spline(x, y, ax=None, spline_type='non-overshoot', num_interp_pts=100, spline_options={}, **plot_kwargs)[source]

Fits a spline to the data points and plots the spline.

Parameters:
xarray-like

X-coordinates of points to interpolate and plot

yarray-like

X-coordinates of points to interpolate and plot

axmatplotlib Axis object, optional

Axes on which to plot, by default creates and returns new figure and axis

spline_typestr, optional

Type of spline from the following list of options (by default non-overshoot):

  • “non-overshoot”: Cubic spline that does not overshoot data (SciPy’s Akima1DInterpolator)

  • “b-spline”: B-spline (SciPy’s make_interp_spline)

num_interp_ptsint, optional

Number of points at which to evaluate the spline (linearly spaced between min and max x values), by default 100

spline_optionsdict, optional

Options to pass to the spline, by default none if spline_type is non-overshoot or sets the spline order to the minimum of 3 and one less than the length of x if b-spline. The available options can be found here:

plot_kwargs

Keyword arguments to pass to matplotlib’s plot function

Returns:
fig, ax

If ax is not provided, generates and returns new matplotlib figure and axis

niceplots.utils.save_figs(fig, name, formats, format_kwargs=None, **kwargs)[source]

Save a figure in multiple formats

Parameters:
figMatplotlib figure

The figure to save

namestr

Output path for the files, e.g “path/to/file/file_name”, no file extension required

formatsstr, list[str]

file formats to save the figure in, e.g. “png”, “pdf”, “svg”

format_kwargsdict, optional

A dictionary of dictionaries, where the keys are the file formats and the values are any keyword arguments that should only be applied to that format. These kwargs will be added to ones passed to all formats, by default None

kwargs

Any keyword arguments to pass to plt.savefig() for all formats