Plotting

update_figure

isopy.tb.update_figure(figure, *, size=None, width=None, height=None, dpi=None, facecolor=None, edgecolor=None, frameon=None, tight_layout=None, constrained_layout=None)[source]

Update the figure options.

See the matplotlib documentation here for more details on these options.

All isopy plotting functions will automatically send any kwargs prefixed with figure_ to this function.

Parameters
  • figure (figure, plt) – A matplotlib Figure object or any object with a .gcf() method that returns a matplotlib Figure object, Such as a matplotlib pyplot instance.

  • size (scalar, (scalar, scalar)) – Either a single value representing both deimensions of a tuple consisting of width and height.

  • width (scalar) – Width of figure in inches

  • height (scalar) – Width of figure in inches

  • dpi (scalar) – Resolution of figure in dots per inch

  • facecolor (str) – The face colour of figure

  • edgecolor (str) – The edge colours of figure

  • frameon (bool) – If False does not draw the figure background colour

  • tight_layout (bool) – If True use tight_layout when drawing the figure.

  • constrained_layout (bool) – If True use constrained_layout when drawing the figure.

Returns

figure – Returns the figure

Return type

Figure

Examples

>>> isopy.tb.update_figure(plt, size=(10,2), facecolor='orange')
>>> isopy.tb.plot_scatter(plt, np.arange(10), np.arange(10))
>>> plt.show()
output of the example above
>>> isopy.tb.plot_scatter(plt, np.arange(10), np.arange(10),
                 figure_size=(10, 2), figure_facecolor='orange')
>>> plt.savefig('update_figure2.png')
output of the example above

update_axes

isopy.tb.update_axes(axes, *, legend=None, **kwargs)[source]

Update axes attributes.

All isopy plotting functions will automatically send any kwargs prefixed with axes_ to this function.

Parameters
  • axes (axes, dict[str, axes]) – A matplotlib axes or a a dictionary of matplotlib axes. In the latter case the options are applied to each axes in the dictionary.

  • legend (bool) – If True the legend will be shown on the axes. If False no legend is shown.

  • kwargs – Any attribute that can be set using axes.set_<key>(value). If the value is a tuple axes.set_<key>(*value) is used. If the value is a dictionary axes.set_<key>(**value).

Examples

>>> isopy.tb.update_axes(plt, xlabel='This it the x-axis', ylabel='This is the y-axis')
>>> isopy.tb.plot_scatter(plt, np.arange(10), np.arange(10))
>>> plt.show()
output of the example above
>>> isopy.tb.plot_scatter(plt, np.arange(10), np.arange(10),
                        axes_xlabel='This it the x-axis',
                        axes_ylabel='This is the y-axis')
>>> plt.show()
output of the example above

create_subplots

isopy.tb.create_subplots(figure, subplots, grid=None, *, row_height=None, column_width=None, legend=None, legend_ratio=None, constrained_layout=True, height_ratios=None, width_ratios=None, **kwargs)[source]

Create subplots for a figure.

Use None instead of a name to create an empty space.

Parameters
  • figure (figure, plt) – A matplotlib Figure object or any object with a .gcf() method that returns a matplotlib Figure object, Such as a matplotlib pyplot instance.

  • subplots (list, int) – A nested list of subplot names. A visual layout of how you want your subplots to be arranged labeled as strings. subplots can be a 1-dimensional list if grid is specified. None will create an empty space. An integer of the number of subplots can be given if grid is specified. Each axes will be names ax<i> e.g. [["ax0", "ax1"], ["ax2", "ax3"]] . A tuple can be passed for twinned axes as (name, [name_twinx], [name_twiny]).

  • grid (tuple[int, int]) – If supplied then subplots will be arranged into grid with this shape. One dimension can be -1 and it wil be calculated based on the size of subplots and the other given dimension. Required that subplots is a one dimensional sequence.

  • row_height – The height of each row in final figure. If height_ratios is given then the height of each row is row_height multiplied by the height ratio.

  • row_height – The width of each column in final figure. If width_ratios is given then the width of each column is column_width multiplied by the width ratio.

  • legend ({"n", "e", "s", "w"}, None) – Creates an additional row/column for the legend at the position indicated. This subplot is given the name “legend” in the output.

  • legend_ratio – The relative size of the legend. If height_ratios or width_ratios has not been given then the value for other each row/column is assumed to be 1.

  • constrained_layout (bool) – If True use constrained_layout when drawing the figure. Advised to avoid overlapping axis labels.

  • height_ratios – A list of the relative height for each row.

  • width_ratios – A list of the relative width of each column.

  • kwargs

    Prefix kwargs to be passed along witht he creation of each subplot with subplot_. Kwargs to be passed to the GridSpec should be prefixed gridspec_. See matplotlib docs for add_subplot

    for a list of avaliable kwargs.

Returns

subplots – A dictionary containing the newly created subplots.

Return type

dict

Examples

>>> subplots = [['one', 'two', 'three', 'four']]
>>> axes = isopy.tb.create_subplots(plt, subplots)
>>> for name, ax in axes.items(): ax.set_title(name)
>>> plt.show()
output of the example above
>>> subplots = ['one', 'two', 'three', 'four', 'five', 'six']
>>> axes = isopy.tb.create_subplots(plt, subplots, (-1, 2))
>>> for name, ax in axes.items(): ax.set_title(name)
>>> plt.show()
output of the example above
>>> subplots = [['one', 'two'], ['three', 'two'], ['four', 'four']]
>>> axes = isopy.tb.create_subplots(plt, subplots)
>>> for name, ax in axes.items(): ax.set_title(name)
>>> plt.show()
output of the example above

Presets

The following presets are avaliable for this function:

  • create_subplots.v(*args, **kwargs, grid = (-1, 1))

  • create_subplots.h(*args, **kwargs, grid = (1, -1))

create_legend

isopy.tb.create_legend(axes, *include_axes, labels=None, hide_axis=None, errorbars=True, newlines=None, **kwargs)[source]

Create a legend encompassing multiple axes.

Items in axes, if there are any, will be included in the legend.

If mutilple axes contains items with the same label then only the item from the last axes is included in the legend. Empty labels or labels beggining with '_' are not included in the legend.

Parameters
  • axes – The axes on which the legend will be drawn. any items in this axes will be included in the legend.

  • include_axes – Items from axes given here will be included in the legend. Accepts a dict containing axes.

  • labels – If given then only items with this label will be included in the legend.

  • hide_axis – If True then the x and y axis of axes will be hidden. If None then the axis is hidden only if include_axes are given and there are not items axes with a label.

  • errorbars – If False then the errobars wont appear on the markers in the legend.

  • newlines – A dictionary of new lines to be created and included in the legend. The key corresponds to the label and the value is another dict of the kwargs for a line.

  • kwargs – Any additional kwargs to be passed when creating the legend. See legend for a list of avaliable kwargs.

Examples

>>> data = isopy.random(100, keys='ru pd cd'.split())
>>> axes = isopy.tb.create_subplots(plt, [['left', 'right']], figure_width=8)
>>> isopy.tb.plot_scatter(axes['left'], data['pd'], data['ru'], label='ru/pd', color='red')
>>> isopy.tb.plot_scatter(axes['right'], data['pd'], data['cd'], label='cd/pd', color='blue')
>>> isopy.tb.create_legend(axes['right'], axes['left'])
>>> plt.show()
output of the example above
>>> data = isopy.random(100, keys='ru pd cd'.split())
>>> axes = isopy.tb.create_subplots(plt, [['left', 'right', 'legend']],
                                    figure_width=9, gridspec_width_ratios=[4, 4, 1])
>>> isopy.tb.plot_scatter(axes['left'], data['pd'], data['ru'], label='ru/pd', color='red')
>>> isopy.tb.plot_scatter(axes['right'], data['pd'], data['cd'], label='cd/pd', color='blue')
>>> isopy.tb.create_legend(axes['legend'], axes, hide_axis=True)
>>> plt.show()
output of the example above

plot_scatter

isopy.tb.plot_scatter(axes, x, y, xerr=None, yerr=None, color=None, marker=True, line=False, regression=None, **kwargs)[source]

Plot data points with error bars on axes.

Parameters
  • axes (axes, plt) – The axes on which the data points will we plotted. Must be a matplotlib axes object or any object with a gca() method that return a matplotlib axes object, such as a matplotlib pyplot instance.

  • x (numpy_array_like) – Any object that can be converted to a numpy array. Multidimensional array will be flattened. x and y must be the same size.

  • y (numpy_array_like) – Any object that can be converted to a numpy array. Multidimensional array will be flattened. x and y must be the same size.

  • xerr (scalar, numpy_array_like) – Uncertainties associated with x and y values. Can be any object that can be converted to a numpy array. Multidimensional array will be flattened. Must either have the same size as x and y or be a single value which will be used for all datapoints. If None no errorbars are shown.

  • yerr (scalar, numpy_array_like) – Uncertainties associated with x and y values. Can be any object that can be converted to a numpy array. Multidimensional array will be flattened. Must either have the same size as x and y or be a single value which will be used for all datapoints. If None no errorbars are shown.

  • color (str, Optional) –

    Color of the marker face and line between points, if marker and line are not False. Accepted strings are named colour in matplotlib or a string of a hex triplet begining with “#”. See here for a list of named colours in matplotlib. If not given the next colour on the internal matplotlib colour cycle is used.

  • marker (bool, str, Default = True) –

    If True a marker is shown for each data point. If False no marker is shown. Can also be a string describing any marker accepted by matplotlib. See here for a list of avaliable markers.

  • line (bool, str, Default = False) –

    If True a line is drawn between each datapoint. If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "solid".

  • regression ({'york1', 'york2', 'linear'}, Optional) – A string with the name of a regression to be applied to the data and then plotted. Valid options are york1, york2, and linear.

  • kwargs

    Any keyword argument accepted by matplotlib axes method errorbar. See here for a list of keyword arguments.

Examples

>>> x = isopy.random(20, seed=46)
>>> y = x * 3 + isopy.random(20, seed=47)
>>> isopy.tb.plot_scatter(plt, x, y)
>>> plt.show()
output of the example above
>>> x = isopy.random(20, seed=46)
>>> y = x * 3 + isopy.random(20, seed=47)
>>> xerr = 0.2
>>> yerr = isopy.random(20, seed=48)
>>> isopy.tb.plot_scatter(plt, x, y, xerr, yerr, regression='york1', color='red', marker='s')
>>> plt.show()
output of the example above

plot_regression

isopy.tb.plot_regression(axes, regression_result, color=None, line=True, xlim=None, autoscale=False, fill=True, edgeline=True, label_equation=True, **kwargs)[source]

Plot the result of a regression on matplotlib axes.

If regression_result has a y_se(x) method the error envelope of the regression will also be plotted.

Parameters
  • axes (axes, plt) – If y is a numpy array axes must be a matplotlib axes object or object with a gca() method that return a matplotlib axes object, such as a matplotlib pyplot instance. If y is an isopy array axes must be a matplotlib Figure or any object with a .gcf() method that returns a matplotlib Figure object, Such as a matplotlib pyplot instance.

  • regression_result – Any object returned by one of isopy’s regression functions, an object with .slope and .intercept attributes or a callable object which takes the x value and returns the y value. Can also be either a single scalar representing the slope or a tuple of two scalars, representing the slope and the intercept.

  • color (str, Optional) –

    Color of the regression line if line is not False. Accepted strings are named colour in matplotlib or a string of a hex triplet begining with “#”. See here for a list of named colours in matplotlib. If not given the next colour on the internal matplotlib colour cycle is used.

  • line (bool, str, Default = True) –

    If True a the regression line is drawn within xlim. If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "solid".

  • xlim (tuple[int, int]) – A tuple of the lower and upper x value for which to plot the regression line. If None the current xlim of the axes is used.

  • autoscale (bool, Default = False) – If False the regression will not be taken into account when figure is rescaled. This if not officially supported by matplotlib and thus might not always work.

  • fill (bool, Default = True) – If True the error enveloped is filled in with color. If False the error envelope is not filled in.

  • edgeline (bool, Default = True) –

    If True the edges of the error envelope are drawn as a line. If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "dashed".

  • label_equation (bool) – If True the equation of the regression line will be added to the label of the regression line.

  • kwargs

    Any keyword argument accepted by matplotlib axes methods. By default kwargs are attributed to the regression line. Prefix kwargs for the fill area with fill_ and kwargs for the edge lines with edgeline_. See here for a list of keyword arguments for the regression line and edge lines. See here for a list of keyword arguments for the fill area.

Examples

>>> x = isopy.random(20, seed=46)
>>> y = x * 3 + isopy.random(20, seed=47)
>>> regression = isopy.tb.regression_linear(x, y)
>>> isopy.tb.plot_scatter(plt, x, y)
>>> isopy.tb.plot_regression(plt, regression)
>>> plt.show()
output of the example above
>>> x = isopy.random(20, seed=46)
>>> y = x * 3 + isopy.random(20, seed=47)
>>> regression = lambda x: 2 * x + x ** 2 #Any callable that takes x and return y is a valid
>>> isopy.tb.plot_scatter(plt, x, y, color='red')
>>> isopy.tb.plot_regression(plt, regression, color='red', xlim=(-1, 1))
>>> plt.show()
output of the example above
>>> x = isopy.random(20, seed=46)
>>> y = x * 3 + isopy.random(20, seed=47)
>>> xerr = 0.2
>>> yerr = isopy.random(20, seed=48)
>>> regression = isopy.tb.regression_york1(x, y, xerr, yerr)
>>> isopy.tb.plot_scatter(plt, x, y, xerr, yerr)
>>> isopy.tb.plot_regression(plt, regression)
>>> plt.show()
output of the example above
>>> x = isopy.random(20, seed=46)
>>> y = x * 3 + isopy.random(20, seed=47)
>>> xerr = 0.2
>>> yerr = isopy.random(20, seed=48)
>>> isopy.tb.plot_scatter(plt, x, y, xerr, yerr, color='red')
>>> isopy.tb.plot_regression(plt, regression, color='red', line='dashed', edgeline=False)
>>> plt.show()
output of the example above

plot_vstack

isopy.tb.plot_vstack(axes, x, xerr=None, ystart=None, *, outliers=None, cval=None, pmval=None, color=None, marker=True, line=False, cline=True, pmline=False, box=True, pad=2, box_pad=None, spacing=-1, hide_yaxis=True, compare=False, subplots_grid=(1, -1), **kwargs)[source]

Plot values along the x-axis at a regular y interval. Also known as Caltech or Carnegie plot.

Can also take an array in which case it will create a grid of subplots, one for each column in the array.

Parameters
  • axes (axes, figure, plt) – If x is a numpy array axes must be a matplotlib axes object or object with a gca() method that return a matplotlib axes object, such as a matplotlib pyplot instance. If x is an isopy array axes must be a matplotlib Figure or any object with a .gcf() method that returns a matplotlib Figure object, Such as a matplotlib pyplot instance.

  • x (numpy_array_like, isopy_array) – Any object that can be converted to a numpy array. Multidimensional array will be flattened. ‘x* and y must be the same size.

  • xerr (numpy_array_like, isopy_array, Optional) – Uncertianties associated with y values. Must be an object that can be converted to a numpy array. Multidimensional array will be flattened. Must either be an array with the same size as y or a single value which will be used for all values of y. If None no errorbars are shown.

  • ystart (scalar, Optional) – The starting valeu on the yaxis. If None it is inferred from values already plotted on the axes. If x is an isopy array the ystart will be the same for all subplots.

  • outliers (bool, Optional) – A boolean array same size as x where True means a data point is considered an outlier.

  • cval (scalar, Callable, Optional) – The center value of the data. Can either be a scalar or a function that returns a scalar when called with x. If cval is a function is it called on the values that are not outliers. If cval is True np.mean is used to calculate cval.

  • pmval (scalar, Callable, Optional) – The uncertainty of the the data. Can either be a scalar or a function that returns a scalar when called with x. If pmval is a function is it called on the values that are not outliers. If pmval is True isopt.sd2 is used to calculate pmval.

  • color (str, Optional) –

    Color of the marker face and line between points, if marker and line are not False. Accepted strings are named colour in matplotlib or a string of a hex triplet begining with “#”. See here for a list of named colours in matplotlib. If not given the next colour on the internal matplotlib colour cycle is used.

  • marker (bool, str, Default = True) –

    If True a marker is shown for each data point. If `False no marker is shown. Can also be a string describing any marker accepted by matplotlib. See here for a list of avaliable markers.

  • line (bool, str, Default = False) –

    If True a line is drawn between each datapoint. If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "solid".

  • cline (bool, str, Default = True) –

    If True a center line is drawn at cval alongside the data points. If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "solid". Only shown if cval is given.

  • pmline (bool, str, Default = False) –

    If True two lines at the upper uncertainty (cval+pmval) and lower uncertainty (cval-pmval) alongside the data points, . If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "solid". Only shown if cval and pmval are given.

  • box (bool, Default = True) – If True a semitransparent box is drawn alongisde the data points basedon the cval and pmval values.

  • pad (scalar, Default = 2) – The space between previous data points and the new data points on the y-axis.

  • box_pad (scalar, Optional) – The space the cline, pmline and box extends past the data points on the y-axis. If None a 1/4 of pad is used.

  • spacing (scalar, Default = 1) – The space between data points on the y-axis.

  • hide_yaxis (bool, Default = True) – Hides the y-axis ticks and label.

  • compare (bool) – If True axes is passed to plot_vcompare at the end of the function.

  • subplots_grid (tuple[int, int]) – The shape of the grid to be created if nessecary.

  • kwargs

    Any keyword argument accepted by matplotlib axes methods. By default kwargs are attributed to the data points. Prefix kwargs for the center line with cline_, kwargs for the plus/minus lines with pmline_ and kwargs for the box area with box_. See here for a list of keyword arguments for the data points. See here for a list of keyword arguments for the center and plus/minus lines. See here for a list of keyword arguments for the box area.

Examples

>>> array1 = isopy.random(100, -0.5, seed=46)
>>> array2 = isopy.random(100, 0.5, seed=47)
>>> isopy.tb.plot_vstack(plt, array1)
>>> isopy.tb.plot_vstack(plt, array2, cval=np.mean, pmval=isopy.sd2)
>>> plt.show()
output of the example above
>>> keys = isopy.keylist('pd105', 'ru101', 'cd111')
>>> array1 = isopy.random(100, -0.5, keys, seed=46)
>>> array2 = isopy.random(100, 0.5, keys, seed=47)
>>> isopy.tb.create_subplots(plt, keys.sorted(), (1, -1))
>>> isopy.tb.plot_vstack(plt, array1)
>>> isopy.tb.plot_vstack(plt, array2, cval=np.mean, pmval=isopy.sd2)
>>> plt.show()
output of the example above
>>> keys = isopy.keylist('pd105', 'ru101', 'cd111')
>>> array = isopy.random(100, -0.5, keys, seed=46)
>>> mean = np.mean(array);
>>> sd = isopy.sd(array)
>>> outliers = isopy.tb.find_outliers(array, mean, sd)
>>> isopy.tb.create_subplots(plt, keys.sorted(), (1, -1))
>>> isopy.tb.plot_vstack(plt, array, cval=mean, pmval=sd, outliers=outliers, color=('red', 'pink'))
>>> plt.show()
output of the example above

plot_vcompare

isopy.tb.plot_vcompare(axes, cval=<function nanmean>, pmval=functools.partial(<function nansd>, zscore=2), sigfig=2, pmunit='diff', cline='-', pmline='--', color='black', axis_color=None, ignore_outliers=True, combine_ticklabels=5)[source]

A comparison plot for data sets on a vstack.

Calculate the center and uncertainty values for all data plotted on a vstack and set the x axis tick marks at [cval-pmval, cval, cval+pmval] and format the tick labels according to pmunit.

Parameters
  • axes (axes, figure, plt) – Either a matplotlib axes object or a matplotlib Figure object. Objects with a gca() method that return a matplotlib axes object, such as a matplotlib pyplot instance are also accepted. If axes is a matplotlib Figure object then plot_vcompare() will be called on every named subplot in the figure.

  • cval (scalar, Callable, Optional) – Either a scalar representing the center value or a function that will be used to calculate the center value based on all the x-axis data points in axes.

  • pmval (scalar, Callable, Optional) – Either a scalar representing the uncertainty on the center value or a function that will be used to calculate the uncertainty based on all the x-axis data points in axes.

  • sigfig (int, Default = 2) – The number of significant figures to be shown on the x-axis tick labels.

  • pmunit (str, Default = 'diff') –

    Defines the unit of the tick labels for the pmline’s. Avaliable options are:

    • "diff" - The tick labels are shown as f'"Δ {+pmval}" and f'"Δ {-pmval}".

    • "abs" - The tick labels are shown as f'"{cval+pmval}" and f'"{cval-pmval}".

    • "percent" or "%" - The tick labels are shown as f'"{+pmval/cval*100} %" and f'"{-pmval/cval*100} %".

    • "permil" or "ppt" - The tick labels are shown as f'"{+pmval/cval*1000} ‰" and f'"{-pmval/cval*1000} ‰".

    • "ppm" - The tick labels are shown as f'"{+pmval/cval*1E6} ppm" and f'"{-pmval/cval*1E6} ppm".

    • "ppb" - The tick labels are shown as f'"{+pmval/cval*1E9} ppb" and f'"{-pmval/cval*1E9} ppb".

    A tuple can be used to set different units for the upper and lower tick labels.

  • cline (bool, str, Default = True) –

    If True a vertical line is drawn along cval. If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "solid".

  • pmline (bool, str, Default = True) –

    If True vertical lines are drawn along cval-pmval` and ``cval+pmval.

    If False no line is shown. Can also

    be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "dashed".

  • color (str, Optional) –

    Color cline and pmline lines. Accepted strings are named colour in matplotlib or a string of a hex triplet begining with “#”. See here for a list of named colours in matplotlib. If None the default value is black.

  • axis_color (bool, str, Optional) – If True the elements on the x-axis are given the same colour as color.

  • ignore_outliers (bool, Default = True) – If True outliers are not used to calculate cval and pmline.

  • combine_ticklabels (bool, scalar, Default = 5) – If True the all three tick labels are combined into the center tick label. This is useful if there isnt enough space to display them all next to each other. If combinde_ticklabels is a scalar then the tick labels are only combined if the difference between the limits and the plus/minus tick label positions exceed this value.

Examples

>>> array1 = isopy.random(100, -0.5, seed=46)
>>> array2 = isopy.random(100, 0.5, seed=47)
>>> isopy.tb.plot_vstack(plt, array1, cval=np.mean, pmval=isopy.sd2)
>>> isopy.tb.plot_vstack(plt, array2, cval=np.mean, pmval=isopy.sd2)
>>> isopy.tb.plot_vcompare(plt)
>>> plt.show()
output of the example above
>>> array1 = isopy.random(100, -0.5, seed=46)
>>> array2 = isopy.random(100, 0.5, seed=47)
>>> isopy.tb.plot_vstack(plt, array1, cval=np.mean, pmval=isopy.sd2)
>>> isopy.tb.plot_vstack(plt, array2, cval=np.mean, pmval=isopy.sd2)
>>> isopy.tb.plot_vcompare(plt, pmval=isopy.sd, sigfig=3)
>>> plt.show()
output of the example above
>>> pmunits = ['diff', 'abs', '%', 'ppt', 'ppm', 'ppb']
>>> subplots = isopy.tb.create_subplots(plt, pmunits, (1, -1), figure_width=8)
>>> array1 = isopy.random(100, 0.9, seed=46)
>>> array2 = isopy.random(100, 1.1, seed=47)
>>> for unit, axes in subplots.items():
        isopy.tb.plot_vstack(axes, array1, cval=np.mean, pmval=isopy.sd2)
        isopy.tb.plot_vstack(axes, array2, cval=np.mean, pmval=isopy.sd2)
        isopy.tb.plot_vcompare(axes, pmval=isopy.sd, pmunit=unit, combine_ticklabels=True)
        axes.set_xlabel(f'pmunit="{unit}"')
>>> plt.show()
output of the example above
>>> keys = isopy.keylist('pd105', 'ru101', 'cd111')
>>> array1 = isopy.random(100, 0.9, keys, seed=46)
>>> array2 = isopy.random(100, 1.1, keys, seed=47)
>>> isopy.tb.plot_vstack(plt, array1)
>>> isopy.tb.plot_vstack(plt, array2, cval=np.mean, pmval=isopy.sd2)
>>> isopy.tb.plot_vcompare(plt.gcf(), combine_ticklabels=True)
>>> plt.show()
output of the example above

plot_hstack

isopy.tb.plot_hstack(axes, y, yerr=None, xstart=None, *, outliers=None, cval=None, pmval=None, color=None, marker=True, line=False, cline=True, pmline=False, box=True, pad=2, box_pad=None, spacing=1, hide_xaxis=True, compare=False, subplots_grid=(-1, 1), **kwargs)[source]

Plot values along the x-axis at a regular y interval. Also known as Caltech or Carnegie plot.

Can also take an array in which case it will create a grid of subplots, one for each column in the array.

Parameters
  • axes (axes, figure, plt) – If y is a numpy array axes must be a matplotlib axes object or object with a gca() method that return a matplotlib axes object, such as a matplotlib pyplot instance. If y is an isopy array axes must be a matplotlib Figure or any object with a .gcf() method that returns a matplotlib Figure object, Such as a matplotlib pyplot instance.

  • y (numpy_array_like, isopy_array) – Any object that can be converted to a numpy array. Multidimensional array will be flattened. x and y must be the same size.

  • yerr (numpy_array_like, isopy_array, Optional) – Uncertianties associated with y values. Must be an object that can be converted to a numpy array. Multidimensional array will be flattened. Must either be an array with the same size as y or a single value which will be used for all values of y. If None no errorbars are shown.

  • xstart (scalar, Optional) – The starting value on the yaxis. If None it is inferred from values already plotted on the axes. If y is an isopy array the xstart will be the same for all subplots.

  • outliers (bool, Optional) – A boolean array same size as y where True means a data point is considered an outlier.

  • cval (scalar, Callable, Optional) – The center value of the data. Can either be a scalar or a function that returns a scalar when called with x. If cval is a function is it called on the values that are not outliers. If cval is True np.mean is used to calculate cval.

  • pmval (scalar, Callable, Optional) – The uncertainty of the the data. Can either be a scalar or a function that returns a scalar when called with x. If pmval is a function is it called on the values that are not outliers. If pmval is True isopt.sd2 is used to calculate pmval.

  • color (str, Optional) –

    Color of the marker face and line between points, if marker and line are not False. Accepted strings are named colour in matplotlib or a string of a hex triplet begining with “#”. See here for a list of named colours in matplotlib. If not given the next colour on the internal matplotlib colour cycle is used.

  • marker (bool, str, Default = True) –

    If True a marker is shown for each data point. If `False no marker is shown. Can also be a string describing any marker accepted by matplotlib. See here for a list of avaliable markers.

  • line (bool, str, Default = False) –

    If True a line is drawn between each datapoint. If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "solid".

  • cline (bool, str, Default = True) –

    If True a center line is drawn at cval alongside the data points. If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "solid". Only shown if cval is given.

  • pmline (bool, str, Default = False) –

    If True two lines at the upper uncertainty (cval+pmval) and lower uncertainty (cval-pmval) alongside the data points, . If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "solid". Only shown if cval and pmval are given.

  • box (bool, Default = True) – If True a semitransparent box is drawn alongisde the data points basedon the cval and pmval values.

  • pad (scalar, Default = 2) – The space between previous data points and the new data points on the x-axis.

  • box_pad (scalar, Optional) – The space the cline, pmline and box extends past the data points on the x-axis. If None a 1/4 of pad is used.

  • spacing (scalar, Default = 1) – The space between data points on the x-axis.

  • hide_yaxis (bool, Default = True) – Hides the x-axis ticks and label.

  • compare (bool) – If True axes is passed to plot_vcompare at the end of the function.

  • subplots_grid (tuple[int, int]) – The shape of the grid to be created if nessecary.

  • kwargs

    Any keyword argument accepted by matplotlib axes methods. By default kwargs are attributed to the data points. Prefix kwargs for the center line with cline_, kwargs for the plus/minus lines with pmline_ and kwargs for the box area with box_. See here for a list of keyword arguments for the data points. See here for a list of keyword arguments for the center and plus/minus lines. See here for a list of keyword arguments for the box area.

Examples

>>> array1 = isopy.random(100, -0.5, seed=46)
>>> array2 = isopy.random(100, 0.5, seed=47)
>>> isopy.tb.plot_hstack(plt, array1)
>>> isopy.tb.plot_hstack(plt, array2, cval=np.mean, pmval=isopy.sd2)
>>> plt.show()
output of the example above
>>> keys = isopy.keylist('pd105', 'ru101', 'cd111')
>>> array1 = isopy.random(100, -0.5, keys, seed=46)
>>> array2 = isopy.random(100, 0.5, keys, seed=47)
>>> isopy.tb.create_subplots(plt, keys.sorted(), (-1, 1))
>>> isopy.tb.plot_hstack(plt, array1)
>>> isopy.tb.plot_hstack(plt, array2, cval=np.mean, pmval=isopy.sd2)
>>> plt.show()
output of the example above
>>> keys = isopy.keylist('pd105', 'ru101', 'cd111')
>>> array = isopy.random(100, -0.5, keys, seed=46)
>>> mean = np.mean(array);
>>> sd = isopy.sd(array)
>>> outliers = isopy.tb.find_outliers(array, mean, sd)
>>> isopy.tb.create_subplots(plt, keys.sorted(), (-1, 1))
>>> isopy.tb.plot_hstack(plt, array, cval=mean, pmval=sd, outliers=outliers, color=('red', 'pink'))
>>> plt.show()
output of the example above

plot_hcompare

isopy.tb.plot_hcompare(axes, cval=<function nanmean>, pmval=functools.partial(<function nansd>, zscore=2), sigfig=2, pmunit='diff', cline=True, pmline=True, color='black', axis_color=None, ignore_outliers=True, combine_ticklabels=5)[source]

A comparison plot for data sets on a hstack.

Calculate the center and uncertainty values for all data plotted on a hstack and set the y axis tick marks at [cval-pmval, cval, cval+pmval] and format the tick labels according to pmunit.

Parameters
  • axes (axes, figure, plt) – Either a matplotlib axes object or a matplotlib Figure object. Objects with a gca() method that return a matplotlib axes object, such as a matplotlib pyplot instance are also accepted. If axes is a matplotlib Figure object then plot_hcompare() will be called on every named subplot in the figure.

  • cval (scalar, Callable, Optional) – Either a scalar representing the center value or a function that will be used to calculate the center value based on all the y-axis data points in axes.

  • pmval (scalar, Callable, Optional) – Either a scalar representing the uncertainty on the center value or a function that will be used to calculate the uncertainty based on all the y-axis data points in axes.

  • sigfig (int, Default = 2) – The number of significant figures to be shown on the y-axis tick labels.

  • pmunit (str, Default = 'diff') –

    Defines the unit of the tick labels for the pmline’s. Avaliable options are:

    • "diff" - The tick labels are shown as f'"Δ {+pmval}" and f'"Δ {-pmval}".

    • "abs" - The tick labels are shown as f'"{cval+pmval}" and f'"{cval-pmval}".

    • "percent" or "%" - The tick labels are shown as f'"{+pmval/cval*100} %" and f'"{-pmval/cval*100} %".

    • "permil" or "ppt" - The tick labels are shown as f'"{+pmval/cval*1000} ‰" and f'"{-pmval/cval*1000} ‰".

    • "ppm" - The tick labels are shown as f'"{+pmval/cval*1E6} ppm" and f'"{-pmval/cval*1E6} ppm".

    • "ppb" - The tick labels are shown as f'"{+pmval/cval*1E9} ppb" and f'"{-pmval/cval*1E9} ppb".

    A tuple can be used to set different units for the upper and lower tick labels.

  • cline (bool, str, Default = True) –

    If True a horizontal line is drawn along cval. If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "solid".

  • pmline (bool, str, Default = True) –

    If True horizontal lines are drawn along cval-pmval` and ``cval+pmval.

    If False no line is shown. Can also

    be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "dashed".

  • color (str, Optional) –

    Color cline and pmline lines. Accepted strings are named colour in matplotlib or a string of a hex triplet begining with “#”. See here for a list of named colours in matplotlib. If None the default value is black.

  • axis_color (bool, str, Optional) – If True the elements on the y-axis are given the same colour as color.

  • ignore_outliers (bool, Default = True) – If True outliers are not used to calculate cval and pmline.

  • combine_ticklabels (bool, scalar, Default = 5) – If True the all three tick labels are combined into the center tick label. This is useful if there isnt enough space to display them all next to each other. If combinde_ticklabels is a scalar then the tick labels are only combined if the difference between the limits and the plus/minus tick label positions exceed this value.

Examples

>>> array1 = isopy.random(100, 0.9, seed=46)
>>> array2 = isopy.random(100, 1.1, seed=47)
>>> isopy.tb.plot_hstack(plt, array1, cval=np.mean, pmval=isopy.sd2)
>>> isopy.tb.plot_hstack(plt, array2, cval=np.mean, pmval=isopy.sd2)
>>> isopy.tb.plot_hcompare(plt)
>>> plt.show()
output of the example above
>>> array1 = isopy.random(100, 0.9, seed=46)
>>> array2 = isopy.random(100, 1.1, seed=47)
>>> isopy.tb.plot_hstack(plt, array1, cval=np.mean, pmval=isopy.sd2)
>>> isopy.tb.plot_hstack(plt, array2, cval=np.mean, pmval=isopy.sd2)
>>> isopy.tb.plot_hcompare(plt, pmval=isopy.sd, sigfig=3)
>>> plt.show()
output of the example above
>>> pmunits = ['diff', 'abs', '%', 'ppt', 'ppm', 'ppb']
>>> subplots = isopy.tb.create_subplots(plt, pmunits, (-1, 1), figure_height=8)
>>> array1 = isopy.random(100, 0.9, seed=46)
>>> array2 = isopy.random(100, 1.1, seed=47)
>>> for unit, axes in subplots.items():
        isopy.tb.plot_hstack(axes, array1, cval=np.mean, pmval=isopy.sd2)
        isopy.tb.plot_hstack(axes, array2, cval=np.mean, pmval=isopy.sd2)
        isopy.tb.plot_hcompare(axes, pmval=isopy.sd, pmunit=unit, combine_ticklabels=True)
        axes.set_ylabel(f'pmunit="{unit}"')
>>> plt.show()
output of the example above
>>> keys = isopy.keylist('pd105', 'ru101', 'cd111')
>>> array1 = isopy.random(100, 0.9, keys, seed=46)
>>> array2 = isopy.random(100, 1.1, keys, seed=47)
>>> isopy.tb.plot_hstack(plt, array1, cval=np.mean, pmval=isopy.sd2)
>>> isopy.tb.plot_hstack(plt, array2, cval=np.mean, pmval=isopy.sd2)
>>> isopy.tb.plot_hcompare(plt.gcf(), combine_ticklabels=True)
>>> plt.show()
output of the example above

plot_spider

isopy.tb.plot_spider(axes, y, yerr=None, x=None, constants=None, xscatter=None, color=None, marker=True, line=True, **kwargs)[source]

Plot data as a spider diagram on matplotlib axes .

Parameters
  • axes (axes, plt) – The axes on which the data points will we plotted. Must be a matplotlib axes object or any object with a gca() method that return a matplotlib axes object, such as a matplotlib pyplot instance.

  • y (numpy_array_like, dict, isopy_array) – Any object that can be converted to an isopy array or an numpy array. Multidimensional array will be flattened. Will be sorted by increasing x values before plotted.

  • yerr (numpy_array_like, dict, isopy_array) – Uncertianties associated with y values. Can be any object that can be converted to a numpy array. Multidimensional array will be flattened. Must either be an array with the same size as y or a single value which will be used for all values of y. If None no errorbars are shown.

  • x (numpy_array_like, isopy_key_list, Optional) – Any object or sequence of object that can be converted to float values. If x is an isotope key list the nass number of each key is used, for ratio key lists the numerator key string is used. An exception is thrown if there is no common denominator. If None and y is an isopy array then x will be inferred from the key strings.

  • constants (dict[scalar, scalar], Optional) – A dictionary mapping constant y values to their x value. Both the key and the value must be scalars.

  • xscatter (scalar, Optional) – If given, xscatter is used to create variation in the x axis values used for each successive set of y values, within the range (X - xscatter, x*+*xscatter). This helps differentiate samples that all pass through the same point.

  • color (str, Optional) –

    Color of the marker face and line between points, if marker and line are not False. Accepted strings are named colour in matplotlib or a string of a hex triplet begining with “#”. See here for a list of named colours in matplotlib. If not given the next colour on the internal matplotlib colour cycle is used.

  • marker (bool, str, Default = True) –

    If True a marker is shown for each data point. If `False no marker is shown. Can also be a string describing any marker accepted by matplotlib. See here for a list of avaliable markers.

  • line (bool, str, Default = True) –

    If True a line is drawn between each datapoint. If False no line is shown. Can also be a string describing a linestyle defined by matplotlib. See here for a list of avaliable linestyles. True defaults to "solid".

  • kwargs

    Any keyword argument accepted by matplotlib axes method errorbar. See here for a list of keyword arguments.

Examples

>>> array = isopy.to_refval.isotope.fraction.to_array(element_symbol='pd')
>>> isopy.tb.plot_spider(plt, array) #Will plot the fraction of each Pd isotope
>>> plt.show()
output of the example above
>>> subplots = isopy.tb.create_subplots(plt, [['left', 'right']])
>>> array = isopy.to_refval.isotope.fraction.to_array(element_symbol='pd').ratio('105pd')
>>> isopy.tb.plot_spider(subplots['left'], array) #The numerator mass numbers are used as x
>>> isopy.tb.plot_spider(subplots['right'], array, constants={105: 1}) #Adds a one for the denominator
>>> plt.show()
output of the example above
>>> subplots = isopy.tb.create_subplots(plt, [['left', 'right']], figwidth=8)
>>> values = {100: [1, 1, -1], 101.5: [0, 0, 0], 103: [-1, 1, -1]} #keys can be floats
>>> isopy.array(values)
>>> isopy.tb.plot_spider(subplots['left'], values) #Impossible to tell the rows apart
>>> isopy.tb.plot_spider(subplots['right'], values, xscatter=0.15) #Much clearer
>>> plt.show()
output of the example above

plot_contours

isopy.tb.plot_contours(axes, x, y, z, zmin=None, zmax=None, levels=100, colors='jet', colorbar=None, label=False, label_levels=None, filled=True, **kwargs)[source]

Create a contour plot on axes from a data grid.

Parameters
  • axes (axes, figure, plt) – Either a matplotlib axes object or a matplotlib Figure object. Objects with a gca() method that return a matplotlib axes object, such as a matplotlib pyplot instance are also accepted. If axes is a matplotlib Figure object then plot_vcompare() will be called on every named subplot in the figure.

  • x – A 1-dimensional array containing the x-axis values.

  • y – A 1-dimensional array containing the y-axis values.

  • z – A 2-dimensional array containing the z-axis values.

  • zmin – The smallest value in the colour map. Any z values smaller than this value will have the same colour as the zmin value.

  • zmax – The largest value in the colour map. Any z values larger than this value will have the same colour as the zmax value.

  • levels – The number of intervals in the colour map. Can also be a sequence of levels to be used.

  • colors – This can either be a list of colours or a single string of the colour map to be used. Names of avaliable colour maps can be found here <https://matplotlib.org/stable/tutorials/colors/colormaps.html#>.

  • colorbar (bool, axes) – If False no colour bar is drawn. If True a colour bar is drawn on the same axes as contours. If colorbar is an axes the colourbar will be drawn on that axes. If None it default to True if filled is True otherwise it is False.

  • label – If True then a label will be added to each label_level.

  • label_levels – The number of intervals to be labeled. Can also be a sequence of levels to be labeled.

  • filled (bool) – If False only contour lines are shown. If `True filled contours are drawn.

  • kwargs – Kwargs prefixed with 'label_ will be sent to to the clabel function. See avaliable options here <https://matplotlib.org/stable/api/contour_api.html#matplotlib.contour.ContourLabeler.clabel>. All other kwargs will be send to the matplotlib functions contour or contourf. See avaliable options here <https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.contour.html>.

Examples

>>> x = np.arange(10)
>>> y = np.arange(10, 101, 10)
>>> z = np.arange(100).reshape((10, 10))
>>> isopy.tb.plot_contours(plt, x, y, z)
>>> plt.show()
output of the example above
>>> element = 'fe'
>>> spike1 = isopy.array(fe54=0, fe56=0, fe57=1, fe58=0)
>>> spike2 = isopy.array(fe54=0, fe56=0, fe57=0, fe58=1)
>>> axes_labels = dict(axes_xlabel = 'Proportion of double spike in double spike-sample mix',
               axes_ylabel='Proportion of spike1 in double spike',
               axes_title = 'Uncertainty in α (1SD)')
>>> dsgrid = isopy.tb.ds_grid(element, spike1, spike2)
>>> isopy.tb.plot_contours(plt, *dsgrid.xyz(), zmin= 0, zmax=0.01, **axes_labels)
>>> plt.show()
output of the example above

plot_text

isopy.tb.plot_text(axes, xpos, ypos, text, rotation=None, fontsize=None, posabs=True, **kwargs)[source]

Add text to plot.

Parameters
  • axes – The axes on which the regression will we plotted. Must be a matplotlib axes object or any object with a gca() method that return a matplotlib axes object, such as a matplotlib pyplot instance.

  • xpos – Position of the text in the plot. If posabs is True then the text is placed at these data coordinates. If posabs is False then the text is placed at this relative position.

  • ypos – Position of the text in the plot. If posabs is True then the text is placed at these data coordinates. If posabs is False then the text is placed at this relative position.

  • text – The text to be included in the plot.

  • rotation – If given the text is rotated anti-clockwise by this many degrees.

  • fontsize – The fontsize of the text.

  • posabs – If True xpos and ypos represents data coordinates. If False xpos and ypos represents the relative position on the axes in the interval 0 to 1.

  • kwargs – Any other valid keyword argument for the matplotlib.axes.Axes.text() method.

plot_box

isopy.tb.plot_box(axes, x=None, y=None, color=None, autoscale=True, **style_kwargs)[source]

Plot a semi-transparent box on axes.

Parameters
  • axes – The axes on which the regression will we plotted. Must be a matplotlib axes object or any object with a gca() method that return a matplotlib axes object, such as a matplotlib pyplot instance.

  • x – Any object that can be converted to a numpy array. If given, both x and y must contain exactly two items, the initial and the final position. If None the value if taken as the axis limit of axes.

  • y – Any object that can be converted to a numpy array. If given, both x and y must contain exactly two items, the initial and the final position. If None the value if taken as the axis limit of axes.

  • color

    Color of the box polygon. Accepted strings are named colour in matplotlib or a string of a hex triplet begining with “#”. See here for a list of named colours in matplotlib. If not given the next colour on the internal matplotlib colour cycle is used.

  • autoscale – If False the regression will not be taken into account when figure is rescaled. This if not officially supported by matplotlib and thus might not always work.

  • style_kwargs

    Any keyword argument accepted a matplotlib polygon object. See here for a list of keyword arguments.

plot_polygon

isopy.tb.plot_polygon(axes, x, y=None, color=None, autoscale=True, **style_kwargs)[source]

Plot a semi-transparent polygon on axes.

Parameters
  • axes – The axes on which the regression will we plotted. Must be a matplotlib axes object or any object with a gca() method that return a matplotlib axes object, such as a matplotlib pyplot instance.

  • x – Any object that can be converted to a numpy array. Must either be a 1-dimensional array the same size as y or a 2-dimensional array with the shape (-1, 2) if y is None. If x is a two dimensional array

  • y – Any object that can be converted to a numpy array. Must be the same size as x. Can be omitted if x is a 2-dimensional array.

  • color

    Color of the polygon. Accepted strings are named colour in matplotlib or a string of a hex triplet begining with “#”. See here for a list of named colours in matplotlib. If not given the next colour on the internal matplotlib colour cycle is used.

  • autoscale – If False the regression will not be taken into account when figure is rescaled. This if not officially supported by matplotlib and thus might not always work.

  • style_kwargs

    Any keyword argument accepted a matplotlib polygon object. See here for a list of keyword arguments.

Markers

class isopy.tb.Markers(style=None)[source]

Rotate through the markers of the current matplotlib style.

Optionally the name of a different style can be passed when creating the object to return the colours of that style.

If a style does not have any markers defined a default list of markers is used. These are circle, square, triangle, diamond, plus, cross, pentagon.

Is a subclass of list. Only new methods/attributes, or methods/attributes that differ from the original implementation, are shown below.

Examples

>>> markers = isopy.tb.Colors()
>>> for i in range(len(markers)):
>>>     isopy.tb.plot_scatter(plt, 1, i, marker=markers.current, markersize=20)
>>>     markers.next()
>>> plt.show()
output of the example above

Colors

class isopy.tb.Colors(style=None)[source]

Rotate through the colors of the current matplotlib style.

Optionally the name of a different style can be passed when creating the object to return the colours of that style.

Is a subclass of list. Only new methods/attributes, or methods/attributes that differ from the original implementation, are shown below.

Examples

>>> colors = isopy.tb.Colors() # Colours can vary depending on the default style
>>> for i in range(len(colors)):
>>>     isopy.tb.plot_scatter(plt, 1, i, color=colors.current, markersize=20)
>>>     colors.next()
>>> plt.show()
output of the example above