pyrolite.util.plot
Utility functions for working with matplotlib.
- Parameters
DEFAULT_CONT_COLORMAP (
matplotlib.colors.ScalarMappable
) – Default continuous colormap.DEFAULT_DICS_COLORMAP (
matplotlib.colors.ScalarMappable
) – Default discrete colormap.USE_PCOLOR (
bool
) – Option to use thematplotlib.pyplot.pcolor()
function in place ofmatplotlib.pyplot.pcolormesh()
.
pyrolite.util.plot.axes
Functions for creating, ordering and modifying
Axes
.
- pyrolite.util.plot.axes.get_ordered_axes(fig)[source]
Get the axes from a figure, which may or may not have been modified by pyrolite functions. This ensures that ordering is preserved.
- pyrolite.util.plot.axes.get_axes_index(ax)[source]
Get the three-digit integer index of a subplot in a regular grid.
- Parameters
ax (
matplotlib.axes.Axes
) – Axis to to get the gridspec index for.- Returns
Rows, columns and axis index for the gridspec.
- Return type
- pyrolite.util.plot.axes.replace_with_ternary_axis(ax)[source]
Replace a specified axis with a ternary equivalent.
- Parameters
ax (
Axes
)- Returns
tax
- Return type
- pyrolite.util.plot.axes.label_axes(ax, labels=[], **kwargs)[source]
Convenience function for labelling rectilinear and ternary axes.
- pyrolite.util.plot.axes.axes_to_ternary(ax)[source]
Set axes to ternary projection after axis creation. As currently implemented, note that this will replace and reorder axes as acecessed from the figure (the ternary axis will then be at the end), and as such this returns a list of axes in the correct order.
- pyrolite.util.plot.axes.check_default_axes(ax)[source]
Simple test to check whether an axis is empty of artists and hasn’t been rescaled from the default extent.
- Parameters
ax (
matplotlib.axes.Axes
) – Axes to check for artists and scaling.- Return type
- pyrolite.util.plot.axes.check_empty(ax)[source]
Simple test to check whether an axis is empty of artists.
- Parameters
ax (
matplotlib.axes.Axes
) – Axes to check for artists.- Return type
- pyrolite.util.plot.axes.init_axes(ax=None, projection=None, minsize=1.0, **kwargs)[source]
Get or create an Axes from an optionally-specified starting Axes.
Link the x, y or both axes across a group of
Axes
.
- pyrolite.util.plot.axes.get_twins(ax, which='y')[source]
Get twin axes of a specified axis.
- Parameters
ax (
matplotlib.axes.Axes
) – Axes to get twins for.which (
str
) – Which twins to get (shared'x'
, shared'y'
or the concatenatation of both,'xy'
).- Return type
Notes
This function was designed to assist in avoiding creating a series of duplicate axes when replotting on an existing axis using a function which would typically create a twin axis.
- pyrolite.util.plot.axes.subaxes(ax, side='bottom', width=0.2, moveticks=True)[source]
Append a sub-axes to one side of an axes.
- Parameters
ax (
matplotlib.axes.Axes
) – Axes to append a sub-axes to.side (
str
) – Which side to append the axes on.width (
float
) – Fraction of width to give to the subaxes.moveticks (
bool
) – Whether to move ticks to the outer axes.- Returns
Subaxes instance.
- Return type
- pyrolite.util.plot.axes.add_colorbar(mappable, **kwargs)[source]
Adds a colorbar to a given mappable object.
Source: http://joseph-long.com/writing/colorbars/
- Parameters
mappable – The Image, ContourSet, etc. to which the colorbar applies.
- Return type
Todo
Where no mappable specificed, get most recent axes, and check for collections etc
pyrolite.util.plot.density
Functions for dealing with kernel density estimation.
- ivar USE_PCOLOR
Option to use the
matplotlib.pyplot.pcolor()
function in place ofmatplotlib.pyplot.pcolormesh()
.- vartype USE_PCOLOR
- pyrolite.util.plot.density.get_axis_density_methods(ax)[source]
Get the relevant density and contouring methods for a given axis.
- Parameters
ax (
matplotlib.axes.Axes
|mpltern.ternary.TernaryAxes
) – Axis to check.- Returns
Relevant functions for this axis.
- Return type
pcolor, contour, contourf
- pyrolite.util.plot.density.percentile_contour_values_from_meshz(z, percentiles=[0.95, 0.66, 0.33], resolution=1000)[source]
Integrate a probability density distribution Z(X,Y) to obtain contours in Z which correspond to specified percentile contours. Contour values will be returned with the same order as the inputs.
- Parameters
z (
numpy.ndarray
) – Probability density function over x, y.percentiles (
numpy.ndarray
) – Percentile values for which to create contours.resolution (
int
) – Number of bins for thresholds between 0. and max(Z)
- Returns
Todo
This may error for a list of percentiles where one or more requested values are below the miniumum threshold. The exception handling should be updated to cater for arrays - where some of the values may be above the minimum.
- pyrolite.util.plot.density.plot_Z_percentiles(*coords, zi=None, percentiles=[0.95, 0.66, 0.33], ax=None, extent=None, fontsize=8, cmap=None, colors=None, linewidths=None, linestyles=None, contour_labels=None, label_contours=True, **kwargs)[source]
Plot percentile contours onto a 2D (scaled or unscaled) probability density distribution Z over X,Y.
- Parameters
coords (
numpy.ndarray
) – Arrays of (x, y) or (a, b, c) coordinates.z (
numpy.ndarray
) – Probability density function over x, y.percentiles (
list
) – Percentile values for which to create contours.ax (
matplotlib.axes.Axes
,None
) – Axes on which to plot. If none given, will create a new Axes instance.extent (
list
,None
) – List or np.ndarray in the form [-x, +x, -y, +y] over which the image extends.fontsize (
float
) – Fontsize for the contour labels.cmap (
matplotlib.colors.ListedColormap
) – Color map for the contours and contour labels.colors (
str
|list
) – Colors for the contours, can optionally be specified in place of cmap.contour_labels (
dict
|list
) – Labels to assign to contours, organised by level.label_contours :class:`bool` – Whether to add text labels to individual contours.
- Returns
Plotted and formatted contour set.
- Return type
Notes
When the contours are percentile based, high percentile contours tend to get washed our with colormapping - consider adding different controls on coloring, especially where there are only one or two contours specified. One way to do this would be via the string based keyword argument colors for plt.contour, with an adaption for non-string colours which post-hoc modifies the contour lines based on the specified colours?
- pyrolite.util.plot.density.conditional_prob_density(y, x=None, logy=False, resolution=5, bins=50, yextent=None, rescale=True, mode='binkde', ret_centres=False, **kwargs)[source]
Estimate the conditional probability density of one dependent variable.
- Parameters
y (
numpy.ndarray
) – Dependent variable for which to calculate conditional probability P(y | X=x)x (
numpy.ndarray
,None
) – Optionally-specified independent index.logy (
bool
) – Whether to use a logarithmic bin spacing on the y axis.resolution (
int
) – Points added per segment via interpolation along the x axis.bins (
int
) – Bins for histograms and grids along the independent axis.yextent (
tuple
) – Extent in the y direction.rescale (
bool
) – Whether to rescale bins to give the same max Z across x.mode (
str
) –Mode of computation.
If mode is
"ckde"
, usestatsmodels.nonparametric.KDEMultivariateConditional()
to compute a conditional kernel density estimate. If mode is"kde"
, use a normal gaussian kernel density estimate. If mode is"binkde"
, use a gaussian kernel density estimate over y for each bin. If mode is"hist"
, compute a histogram.ret_centres (
bool
) – Whether to return bin centres in addtion to histogram edges, e.g. for later contouring.
- Returns
x
bin edgesxe
,y
bin edgesye
, histogram/density estimatesZ
. Ifret_centres
isTrue
, the last two return values will contain the bin centresxi
,yi
.- Return type
pyrolite.util.plot.export
Functions for export of figures and figure elements from matplolib.
- pyrolite.util.plot.export.save_figure(figure, name='fig', save_at='', save_fmts=['png'], **kwargs)[source]
Save a figure at a specified location in a number of formats.
- pyrolite.util.plot.export.save_axes(ax, name='fig', save_at='', save_fmts=['png'], pad=0.0, **kwargs)[source]
Save either a single or multiple axes (from a single figure) based on their extent. Uses the save_figure procedure to save at a specific location using a number of formats.
Todo
Add legend to items
- pyrolite.util.plot.export.get_full_extent(ax, pad=0.0)[source]
Get the full extent of an axes, including axes labels, tick labels, and titles. Text objects are first drawn to define the extents.
- Parameters
ax (
matplotlib.axes.Axes
) – Axes of which to check items to get full extent.pad (
float
|tuple
) – Amount of padding to add to the full extent prior to returning. If a tuple is passed, the padding will be as above, but for x and y directions, respectively.
- Returns
Bbox of the axes with optional additional padding.
- Return type
pyrolite.util.plot.grid
Gridding and binning functions.
- pyrolite.util.plot.grid.bin_centres_to_edges(centres, sort=True)[source]
Translates point estimates at the centres of bins to equivalent edges, for the case of evenly spaced bins.
Todo
This can be updated to unevenly spaced bins, just need to calculate outer bins.
- pyrolite.util.plot.grid.bin_edges_to_centres(edges)[source]
Translates edges of histogram bins to bin centres.
- pyrolite.util.plot.grid.ternary_grid(data=None, nbins=10, margin=0.001, force_margin=False, yscale=1.0, tfm=<function <lambda>>)[source]
Construct a graphical linearly-spaced grid within a ternary space.
- Parameters
data (
numpy.ndarray
) – Data to construct the grid around ((samples, 3)
).nbins (
int
) – Number of bins for grid.margin (
float
) – Proportional value for the position of the outer boundary of the grid.forge_margin (
bool
) – Whether to enforce the grid margin.yscale (
float
) – Y scale for the specific ternary diagram.tfm – Log transform to use for the grid creation.
- Returns
bins (
numpy.ndarray
) – Bin centres along each of the ternary axes ((samples, 3)
)binedges (
numpy.ndarray
) – Position of bin edges.centregrid (
list
ofnumpy.ndarray
) – Meshgrid of bin centres.edgegrid (
list
ofnumpy.ndarray
) – Meshgrid of bin edges.
pyrolite.util.plot.helpers
matplotlib helper functions for commong drawing tasks.
- pyrolite.util.plot.helpers.alphalabel_subplots(ax, fmt='{}', xy=(0.03, 0.95), ha='left', va='top', **kwargs)[source]
Add alphabetical labels to a successive series of subplots with a specified format.
- Parameters
ax (
list
|numpy.ndarray
|numpy.flatiter
) – Axes to label, in desired order.fmt (
str
) – Format string to use. To add e.g. parentheses, you could specify"({})"
.xy (
tuple
) – Position of the labels in axes coordinates.ha (
str
) – Horizontal alignment of the labels ({"left", "right"}
).va (
str
) – Vertical alignment of the labels ({"top", "bottom"}
).
- pyrolite.util.plot.helpers.get_centroid(poly)[source]
Centroid of a closed polygon using the Shoelace formula.
- Parameters
poly (
matplotlib.patches.Polygon
) – Polygon to obtain the centroid of.- Returns
cx, cy – Centroid coordinates.
- Return type
- pyrolite.util.plot.helpers.get_visual_center(poly, vertical_exaggeration=1)[source]
Visual center of a closed polygon.
- Parameters
poly (
matplotlib.patches.Polygon
) – Polygon for which to obtain the visual center.vertical_exaggeration (
float
) – Apparent vertical exaggeration of the plot (pixels per unit in y direction divided by pixels per unit in the x direction).
- Returns
cx, cy – Centroid coordinates.
- Return type
- pyrolite.util.plot.helpers.rect_from_centre(x, y, dx=0, dy=0, **kwargs)[source]
Takes an xy point, and creates a rectangular patch centred about it.
- pyrolite.util.plot.helpers.draw_vector(v0, v1, ax=None, **kwargs)[source]
Plots an arrow represnting the direction and magnitue of a principal component on a biaxial plot.
Modified after Jake VanderPlas’ Python Data Science Handbook https://jakevdp.github.io/PythonDataScienceHandbook/ 05.09-principal-component-analysis.html
Todo
Update for ternary plots.
- pyrolite.util.plot.helpers.vector_to_line(mu: array, vector: array, variance: float, spans: int = 4, expand: int = 10)[source]
Creates an array of points representing a line along a vector - typically for principal component analysis. Modified after Jake VanderPlas’ Python Data Science Handbook https://jakevdp.github.io/PythonDataScienceHandbook/ 05.09-principal-component-analysis.html
- pyrolite.util.plot.helpers.plot_stdev_ellipses(comp, nstds=4, scale=100, resolution=1000, transform=None, ax=None, **kwargs)[source]
Plot covariance ellipses at a number of standard deviations from the mean.
- Parameters
comp (
numpy.ndarray
) – Composition to use.nstds (
int
) – Number of standard deviations from the mean for which to plot the ellipses.scale (
float
) – Scale applying to all x-y data points. For intergration with python-ternary.transform (
callable
) – Function for transformation of data prior to plotting (to either 2D or 3D).ax (
matplotlib.axes.Axes
) – Axes to plot on.
- Returns
ax
- Return type
- pyrolite.util.plot.helpers.plot_pca_vectors(comp, nstds=2, scale=100.0, transform=None, ax=None, colors=None, linestyles=None, **kwargs)[source]
Plot vectors corresponding to principal components and their magnitudes.
- Parameters
comp (
numpy.ndarray
) – Composition to use.nstds (
int
) – Multiplier for magnitude of individual principal component vectors.scale (
float
) – Scale applying to all x-y data points. For intergration with python-ternary.transform (
callable
) – Function for transformation of data prior to plotting (to either 2D or 3D).ax (
matplotlib.axes.Axes
) – Axes to plot on.
- Returns
ax
- Return type
Todo
Minor reimplementation of the sklearn PCA to avoid dependency.
- pyrolite.util.plot.helpers.plot_2dhull(data, ax=None, splines=False, s=0, **plotkwargs)[source]
Plots a 2D convex hull around an array of xy data points.
- pyrolite.util.plot.helpers.plot_cooccurence(arr, ax=None, normalize=True, log=False, colorbar=False, **kwargs)[source]
Plot the co-occurence frequency matrix for a given input.
- Parameters
ax (
matplotlib.axes.Axes
,None
) – The subplot to draw on.normalize (
bool
) – Whether to normalize the cooccurence to compare disparate variables.log (
bool
) – Whether to take the log of the cooccurence.colorbar (
bool
) – Whether to append a colorbar.
- Returns
Axes on which the cooccurence plot is added.
- Return type
- pyrolite.util.plot.helpers.nan_scatter(xdata, ydata, ax=None, axes_width=0.2, **kwargs)[source]
Scatter plot with additional marginal axes to plot data for which data is partially missing. Additional keyword arguments are passed to matplotlib.
- Parameters
xdata (
numpy.ndarray
) – X dataydata (class:numpy.ndarray | pd.Series) – Y data
ax (
matplotlib.axes.Axes
) – Axes on which to plot.axes_width (
float
) – Width of the marginal axes.
- Returns
Axes on which the nan_scatter is plotted.
- Return type
- pyrolite.util.plot.helpers.init_spherical_octant(angle_indicated=30, labels=None, view_init=(25, 55), fontsize=10, **kwargs)[source]
Initalize a figure with a 3D octant of a unit sphere, appropriately labeled with regard to angles corresponding to the handling of the respective compositional data transformation function (
sphere()
).- Parameters
- Returns
ax – Initialized 3D axis.
- Return type
matplotlib.axes.Axes3D
pyrolite.util.plot.interpolation
Line interpolation for matplotlib lines and paths.
- pyrolite.util.plot.interpolation.interpolate_path(path, resolution=100, periodic=False, aspath=True, closefirst=False, **kwargs)[source]
Obtain the interpolation of an existing path at a given resolution. Keyword arguments are forwarded to
scipy.interpolate.splprep()
.- Parameters
path (
matplotlib.path.Path
) – Path to interpolate.resolution :class:`int` – Resolution at which to obtain the new path. The verticies of the new path will have shape (resolution, 2).
periodic (
bool
) – Whether to use a periodic spline.periodic (
bool
) – Whether to return amatplotlib.path.Path
, or simply a tuple of x-y arrays.closefirst (
bool
) – Whether to first close the path by appending the first point again.
- Returns
Interpolated
Path
object, if aspath isTrue
, else a tuple of x-y arrays.- Return type
- pyrolite.util.plot.interpolation.interpolated_patch_path(patch, resolution=100, **kwargs)[source]
Obtain the periodic interpolation of the existing path of a patch at a given resolution.
- Parameters
patch (
matplotlib.patches.Patch
) – Patch to obtain the original path from.resolution :class:`int` – Resolution at which to obtain the new path. The verticies of the new path will have shape (resolution, 2).
- Returns
Interpolated
Path
object.- Return type
- pyrolite.util.plot.interpolation.get_contour_paths(src, resolution=100, minsize=3)[source]
Extract the paths of contours from a contour plot.
- Parameters
ax (
matplotlib.axes.Axes
|) – Axes to extract contours from.resolution (
int
) – Resolution of interpolated splines to return.
- Returns
contourspaths (
list
(list
)) – List of lists, each represnting one line collection (a single contour). In the case where this contour is multimodal, there will be multiple paths for each contour.contournames (
list
) – List of names for contours, where they have been labelled, and there are no other text artists on the figure.contourstyles (
list
) – List of styles for contours.
Notes
This method assumes that contours are the only
matplotlib.collections.LineCollection
objects within an axes; and when this is not the case, additional non-contour objects will be returned.
pyrolite.util.plot.legend
Functions for creating and modifying legend entries for matplotlib.
Todo
Functions for working with and modifying legend entries.
ax.lines + ax.patches + ax.collections + ax.containers, handle ax.parasites
- pyrolite.util.plot.legend.proxy_rect(**kwargs)[source]
Generates a legend proxy for a filled region.
- Return type
- pyrolite.util.plot.legend.proxy_line(**kwargs)[source]
Generates a legend proxy for a line region.
- Return type
- pyrolite.util.plot.legend.modify_legend_handles(ax, **kwargs)[source]
Modify the handles of a legend based for a single axis.
- Parameters
ax (
matplotlib.axes.Axes
) – Axis for which to obtain modifed legend handles.- Returns
pyrolite.util.plot.style
Functions for automated plot styling and argument handling.
- ivar DEFAULT_CONT_COLORMAP
Default continuous colormap.
- vartype DEFAULT_CONT_COLORMAP
matplotlib.colors.ScalarMappable
- ivar DEFAULT_DISC_COLORMAP
Default discrete colormap.
- vartype DEFAULT_DISC_COLORMAP
matplotlib.colors.ScalarMappable
- pyrolite.util.plot.style.linekwargs(kwargs)[source]
Get a subset of keyword arguments to pass to a matplotlib line-plot call.
- pyrolite.util.plot.style.scatterkwargs(kwargs)[source]
Get a subset of keyword arguments to pass to a matplotlib scatter call.
- pyrolite.util.plot.style.marker_cycle(markers=['D', 's', 'o', '+', '*'])[source]
Cycle through a set of markers.
- Parameters
markers (
list
) – List of markers to provide to matplotlib.
- pyrolite.util.plot.style.mappable_from_values(values, cmap=<matplotlib.colors.ListedColormap object>, norm=None, **kwargs)[source]
Create a scalar mappable object from an array of values.
- Return type
- pyrolite.util.plot.style.ternary_color(tlr, alpha=1.0, colors=([1, 0, 0], [0, 1, 0], [0, 0, 1]), coefficients=(1, 1, 1))[source]
Color a set of points by their ternary combinations of three specified colors.
- Parameters
tlr (
numpy.ndarray
)alpha (
float
) – Alpha coefficient for the colors; to be applied multiplicatively with any existing alpha value (for RGBA colors specified).colors (
tuple
) – Set of colours corresponding to the top, left and right verticies, respectively.coefficients (
tuple
) – Coefficients for the ternary data to adjust the centre.
- Returns
Color array for the ternary points.
- Return type
- pyrolite.util.plot.style.color_ternary_polygons_by_centroid(ax=None, patches=None, alpha=1.0, colors=([1, 0, 0], [0, 1, 0], [0, 0, 1]), coefficients=(1, 1, 1))[source]
Color a set of polygons within a ternary diagram by their centroid colors.
- Parameters
ax (
matplotlib.axes.Axes
) – Ternary axes to check for patches, if patches is not supplied.patches (
list
) – List of ternary-hosted patches to apply color to.alpha (
float
) – Alpha coefficient for the colors; to be applied multiplicatively with any existing alpha value (for RGBA colors specified).colors (
tuple
) – Set of colours corresponding to the top, left and right verticies, respectively.coefficients (
tuple
) – Coefficients for the ternary data to adjust the centre.
- Returns
patches – List of patches, with updated facecolors.
- Return type
pyrolite.util.plot.transform
Transformation utilites for matplotlib.
- pyrolite.util.plot.transform.affine_transform(mtx=array([[1, 0, 0], [0, 1, 0], [0, 0, 1]]))[source]
Construct a function which will perform a 2D affine transform based on a 3x3 affine matrix.
- Parameters
mtx (
numpy.ndarray
)
- pyrolite.util.plot.transform.tlr_to_xy(tlr)[source]
Transform a ternary coordinate system (top-left-right) to an xy-cartesian coordinate system.
- Parameters
tlr (
numpy.ndarray
) – Array of shape (n, 3) in the t-l-r coordinate system.- Returns
xy – Array of shape (n, 2) in the x-y coordinate system.
- Return type
- pyrolite.util.plot.transform.xy_to_tlr(xy)[source]
- Parameters
xy (
numpy.ndarray
) – Array of shape (n, 2) in the x-y coordinate system.- Returns
tlr – Array of shape (n, 3) in the t-l-r coordinate system.
- Return type
- pyrolite.util.plot.transform.ABC_to_xy(ABC, xscale=1.0, yscale=1.0)[source]
Convert ternary compositional coordiantes to x-y coordinates for visualisation within a triangle.
- Parameters
ABC (
numpy.ndarray
) – Ternary array (samples, 3
).xscale (
float
) – Scale for x-axis.yscale (
float
) – Scale for y-axis.
- Returns
Array of x-y coordinates (
samples, 2
)- Return type
- pyrolite.util.plot.transform.xy_to_ABC(xy, xscale=1.0, yscale=1.0)[source]
Convert x-y coordinates within a triangle to compositional ternary coordinates.
- Parameters
xy (
numpy.ndarray
) – XY array (samples, 2
).xscale (
float
) – Scale for x-axis.yscale (
float
) – Scale for y-axis.
- Returns
Array of ternary coordinates (
samples, 3
)- Return type