Primary Functions

These functions form the core functionality of the stratapy package and are categorised into four main areas: loading data, plotting functions (beyond Log.plot() which is documented in the Log Class section), and customising lithologies, features and minerals.

Loading Data

stratapy.core.load(filepath: str, grain_preset: str = 'clastic', x_ticks_dict=None, grain_brackets=None) LogObject

Reads in a file containing stratigraphic data and sets up the necessary variables for plotting.

Supported file formats: .csv, .txt, .xlsx, .xls. Desired column headers: [‘height/age’, ‘rock’, ‘thickness’, ‘bottom_grain’, ‘top_grain’, ‘connection_type’, ‘erosion’, ‘lenses’, ‘minerals’, ‘features’, ‘contact’].

See the documentation for more details on the expected format and structure of the input file.

Parameters:
  • filepath (str) – The path to the input file.

  • grain_preset (str, optional) –

    Various default collections of grain sizes are available for different disciplines. Each one automatically passes a different x_ticks_dict and grain_brackets to the function. Options are ‘clastic’ (default), ‘volcanic’, ‘sedimentary’, ‘dunham’, and ‘clastic’. Alternatively, you can provide your own x_ticks_dict and grain_brackets directly, in which case this parameter is ignored. See See the documentation for details and examples of this functionality.

  • x_ticks_dict (dict, optional) – A dictionary of x-tick labels and their corresponding values of grain size. Adjusting the labels and values will change where the x-ticks are placed on a log’s x-axis. The labels should be unique strings; to have two separate labels for ‘f’ (e.g., ‘f’ for fine ash and ‘f’ for fine lapilli), suffix the string with any of [*, ^, &, _, £, $] to make it unique (these characters will be removed when displayed on the axis).

  • grain_brackets (dict, optional) – A dictionary defining ranges of grain sizes where labelled brackets will be drawn. Each key of the dict is the label of a bracket, and the value is a list of consecutive grain sizes that will be included in the bracket. Grain sizes must match those in the x_ticks_dict.

Returns:

LogObject – An instance of the LogObject class containing the loaded data and set up variables.

Return type:

object

Raises:
  • FileNotFoundError – If the file is not found.

  • ValueError – If the file is not a valid CSV or does not contain the required columns.

Examples

>>> import stratapy as sp
>>> log = sp.load('path/to/your/data.csv')   # Initialise a visualisation
>>> log.plot()                               # Create the figure

Alternatively, you can change the grain size presets:

>>> log = sp.load('path/to/your/data.csv', grain_preset='volcanic')
>>> log.plot()

Or provide your own grain size ticks and brackets:

>>> x_ticks = {'ash': 0.5, 'lapilli': 2, 'bomb': 64, 'block': 256}
>>> grain_brackets = {'coarse': ['lapilli', 'bomb', 'block']}
>>> log = sp.load('path/to/your/data.csv', x_ticks_dict=x_ticks, grain_brackets=grain_brackets)

Plotting Multiple Logs

stratapy.core.correlated_logs(files, left_y_axis: bool = True, offsets: array - like = None, spine_distance: float = 30, fig_kwargs: dict = {}, **kwargs) MultiLogObject

The correlated_logs() function is designed for side-by-side log plots, allowing for easy visual correlation between multiple stratigraphic logs. Unlike multi_fig(), logs have no axes of their own, and instead share a common y-axis, which can be styled as desired.

The function accepts any of the parameters available in the LogObject.plot() method, allowing for extensive customisation of the appearance and layout of the logs, though it is optimised for logs displayed in ‘log’ mode, without grain size axes. Similarly, since the y-axis is shared, it is recommended to ensure that all logs have compatible y-axes (e.g., all in age, or all in depth/height).

In addition, this function accept other parameters to control the style and layout of the figure; see below.

Parameters:
  • files (array-like) – A list, numpy array, or iterable of file paths to the stratigraphic data files to be plotted. Each file will be loaded and plotted as a separate log.

  • left_y_axis (bool, optional) – If True, a single y-axis will be created on the left side of the first log, shared by all logs. Default is False, meaning each log will have its own y-axis on the left side.

  • offsets (array-like, optional) – An iterable of numeric offsets to apply to the y-axis of each log. The length of the list must match the number of files provided. Offsets are applied as follows: for ‘depth’ or ‘age’ y-modes, the offset is subtracted from the y-values; for ‘height’ y-mode, the offset is added to the y-values. Default is None, meaning no offsets are applied.

  • fig_kwargs (dict, optional) – A dictionary of keyword arguments to be passed to the matplotlib.pyplot.subplots() function when creating the figure and axes.

  • **kwargs – Additional keyword arguments to be passed to the LogObject.plot() method for each log.

Returns:

MultiLogObject – An instance of the MultiLogObject class containing the figure, axes, logs, and legend.

Return type:

object

Notes

  • use the y_label parameter to set a shared y-axis label for all logs, if desired.

stratapy.core.multi_fig(files, nrows: int = 1, ncols: int = -1, sharey: bool = False, sharex: bool = False, fig: plt.Figure = None, axes: plt.Axes = None, fig_kwargs: dict = {}, **kwargs) MultiLogObject

This function enables the plotting of multiple logs in a single figure, critically, with a shared legend. Each log is plotted on its own axis, allowing for individual customisation while maintaining a cohesive overall appearance. All optional parameters available in the LogObject.plot() method can be passed to this function, but are shared across all logs for consistency.

Parameters:
  • files (array-like) – An list, numpy array, or other iterable of file paths to stratigraphic data files. Each file should be in a supported format and contain the required columns.

  • nrows (int, optional) – The number of rows in the figure. Default is 1.

  • ncols (int, optional) – The number of columns in the figure. Default is -1, which will fit the number of columns to the number of files provided.

  • sharey (bool, optional) – If True, all logs will share the same y-axis limits. Default is False.

  • sharex (bool, optional) – If True, all logs will share the same x-axis limits. Default is False.

  • fig (matplotlib.figure.Figure, optional) – Matplotlib figure object to plot the logs on. If None, a new figure will be created. axes must also be provided if a custom fig is provided else a new figure will be created.

  • axes (list of matplotlib.axes.Axes, optional) – List of matplotlib axes objects to plot the logs on. If None, new axes will be created. fig must also be provided if custom axes are provided else new axes will be created.

  • fig_kwargs (dict, optional) – A dictionary of keyword arguments to be passed to plt.subplots() when creating a new figure.

  • **kwargs (dict) – Additional keyword arguments to be passed to the LogObject.plot() method for each log

Returns:

MultiLogObject – An instance of the MultiLogObject class containing the figure, axes, logs, and legend.

Return type:

object

Notes

If a custom fig and axes are provided, multi_fig’s sharey and sharex should be used instead of the sharey and sharex parameters of plt.subplots(). Validation of custom fig and axes variables is minimal.

Standalone Plotting Functions

stratapy.core.chronostratigraphy(lower_age: float, upper_age: float, fig: plt.Figure = None, ax: plt.Axes = None, ranks_to_display: list = [0, 1, 2, 3, 4, 5], unit: str = 'Ma', orientation: str = 'vertical', figsize: tuple = None) plt.Axes

Creates a chronostratigraphic timescale on the given axis, vertically or horizontally.

Parameters:
  • lower_age (float) – The lower age limit for the timescale in Ma.

  • upper_age (float) – The upper age limit for the timescale in Ma.

  • fig (matplotlib.figure.Figure, optional) – The figure to draw the timescale on. Default is None, in which a new figure will be created. If a custom figure is provided, a custom axis must also be provided.

  • ax (matplotlib.axes.Axes, optional) – The axis to draw the timescale on. Default is None, in which a new axis will be created. If a custom axis is provided, a custom figure must also be provided.

  • ranks_to_display (list, optional) – A list of ranks to display on the timescale.

  • unit (str, optional) – The unit for the age scale; this will determine what values lower_age and upper_age are interpreted as, and this scale will be used for the x-axis and its label. Default is ‘Ma’ (millions of years). Options are ‘Ma’ (millions of years), ‘ka’ (thousands of years), and ‘a’ (years).

  • orientation (str, optional) – ‘vertical’ (default) or ‘horizontal’ for horizontal timescale.

  • figsize (tuple, optional) – The size of the figure to create if no custom figure and axis are provided. Default is (3, 8) for a vertical timescale or (8, 3) for a horizontal timescale.

Returns:

ax – The axis with the timescale drawn on it.

Return type:

matplotlib.axes.Axes

Notes

The timescale is the International Chronostratigraphic Chart from the International Commission on Stratigraphy, which is updated periodically. The data for the timescale is stored in the package and can be updated by the user if desired; see the documentation for more information. See the tutorial notebook for examples of this function.

Examples

>>> import stratapy as sp
>>> # Create a vertical timescale from 0 to 500 Ma
>>> sp.chronostratigraphy(0, 500)
>>>
>>> # Create a horizontal timescale from 237 to 242 Ma, with a custom figure size and only displaying the period, epoch, and age ranks
>>> sp.chronostratigraphy(237, 242, orientation='horizontal', figsize=(10, 3), ranks_to_display=[3,4,5])
stratapy.core.standalone_legend(files, dpi=300, transparent=True, filename='legend.png', legend_loc='right', legend_columns=1, legend_border=False, legend_kwargs={})

This function will create only the legend of the logs provided in files, which can be used when a legend is wanted without plotting the full log, or when a shared legend is wanted across multiple logs plotted separately, if not using the correlated_logs() or multi_fig() functions which automatically share legends.

By passing custom input files, this function can also be used to create a legend for a non-stratapy plot, or to create a more customised legend.

Parameters:
  • files (list) – A list of file paths to the stratigraphic data files to be included in the legend. Must be files that can be read by the load() function.

  • dpi (int, optional) – The resolution of the figure in dots per inch. Default is 300.

  • transparent (bool, optional) – If True, the background of the saved legend will be transparent. Default is True.

  • filename (str, optional) – The name of the file to save the legend to. Default is ‘legend.png’. The file extension determines the format of the saved legend.

  • legend_loc (str, optional) – The location of the legend on the figure. Default is ‘right’. See matplotlib.legend.Legend documentation for more details on available options.

  • legend_columns (int, optional) – The number of columns to use in the legend. Default is 1.

  • legend_border (bool, optional) – If True, a border will be drawn around the legend. Default is False.

  • legend_kwargs (dict, optional) – Additional keyword arguments to pass to the legend function, such as frameon, etc. Default is an empty dictionary. Note: this will be overriden by the legend_loc, legend_columns, and legend_border parameters, if they are provided.

Return type:

None

stratapy.core.list_examples(return_list: bool = False)

Returns a list of all the .csv example files built into stratapy.

These files can be use by calling sp.load('examples.XXX.csv').

Parameters:

return_list (bool, optional) – If True, the list of example files will be returned as a list of strings. If False, the list will be printed to the console. Default is False.

Returns:

A list of the example files available in stratapy, if return_list is True. Otherwise, the list is printed to the console and None is returned.

Return type:

list

Examples

>>> # To use the `tutorial.csv` example file, call:
>>> log = sp.load('examples.tutorial.csv')

Customising Assets

stratapy.core.update_lithologies(patterns: dict) None

In development : To update lithologies, the user can provide a dictionary of new keys, each with a tuple of length three as its value. Existing keys cannot be changed, but new keys can be added using the format (existing pattern or filepath, colour (optional), name), the only exception being the ‘no observation’ lithology, which can be changed to a new name (there is no fill colour so it takes the background of the figure). Lithology keys are all case insensitive.

Parameters:

patterns (dict) –

A dictionary of the lithologies to be added to the user’s data in the format {key: (pattern/existing key/filepath, colour, name)}. The pattern can be an existing lithology key (e.g., ‘sandstone’), or a filepath to a custom image (e.g., ‘path/to/image.png’).

The colour can be a matplotlib colormap name, a colour string, or an RGB tuple; the code will attempt to convert automatically. If using a custom image, the colour is ignored.

The name is the string that will be displayed in the legend for this lithology.

Return type:

None

Examples

>>> import stratapy as sp
>>> sp.update_lithologies( {
>>>     # A simple colour fill
>>>     'clay': ('', '#A53535', 'Clay'),
>>>     # A variation on an existing pattern with a new colour
>>>     'new_sandstone': ('sandstone', 'tan', 'New sandstone'),
>>>     # Naming a pattern lithology
>>>     'soil': ('117', 'w', 'Soil'),
>>>     # A custom image
>>>     'custom': ('path/to/image.png', '', 'Custom lithology'),
>>> })

Notes

  • Supported formats for custom images are: ‘.png’, ‘.jpg’, ‘.jpeg’, ‘.bmp’, ‘.gif’, ‘.tiff’.

stratapy.core.update_features(new_features: dict) None

This function enables the addition or editing of features in stratapy. The user can provide a dictionary of new keys, each with a tuple of length three as its value. Existing keys cannot be changed, but new keys can be added using the format (type, filepath, name). The type can be ‘fossil’, ‘structure’, or ‘tectonic’ (or ‘f’, ‘s’, ‘t’ for short), and the filepath can be an existing feature key or a valid filepath to a custom image. Feature keys are case insensitive.

Parameters:

new_features (dict) – A dictionary of the features to be added to the user’s data in the format {key: (type, filepath, name)}. The type can be ‘fossil’, ‘structure’, or ‘tectonic’ (or ‘f’, ‘s’, ‘t’ for short). The filepath can be an existing feature key or a valid filepath to a custom image. The name is the string that will be displayed in the legend for this feature.

Return type:

None

Examples

>>> import stratapy as sp
>>> sp.update_features( {
>>>     # Renames the default 'normal grading' feature to 'Grading' in the legend
>>>     'normal grading': ('', '', 'Grading'),
>>>     # Moves the default 'Mollusc' feature to the sedimentary structures group
>>>     'mollusc': ('structure', '', 'Mollusc'),
>>>     # Moves the default 'Bioturbation (med.)' feature to the fossils group, and re-names to 'Bioturbation'
>>>     'bioturbation medium': ('f', '', 'Bioturbation'),
>>>     # Creates a new 'Scaphopod' feature using the default trace fossil image and type
>>>     'scaphopod': ('', 'trace fossil', 'Scaphopod'),
>>>     # Adds a new fossil feature with a custom image and name
>>>     'my_fossil': ('fossil', 'my_fossil.png', 'My Fossil'),
>>> } )
stratapy.core.update_minerals(minerals: dict) None

Enables the formatting of existing minerals to be updated, or new minerals to be added to the package.

Parameters:

minerals (dict) – A dictionary of the minerals to be added to the user’s data in the format {key: (fillcolour, edgecolour, shape)}. The fillcolour and edgecolour can be RGB tuples, matplotlib color strings, or hex codes; the code will attempt to convert automatically. The key is the name of the mineral; it is case sensitive, with the title case version used in the legend. Shape is any of the matplotlib markers.

Examples

>>> import stratapy as sp
>>> sp.update_minerals( {
>>>     # Magenta diamond with black edge - overrides default garnet style
>>>     'garnet': ('#FF00FF', 'k', 'd'),
>>>     # Orange circle with brown edge - new mineral
>>>     'honeystone': ('orange', 'brown', 'o'),
>>> } )
>>>
>>> # 'garnet' is available by default, so this will update it
>>> sp.update_minerals({'garnet': ((1, 0, 0), 'red', 'o')})
>>> # 'granite' is not available by default, so this will add it
>>> sp.update_minerals({'granite': ('#FF0000', 'r', 'o')})