mtpy.imaging.mtplot_tools package
Submodules
mtpy.imaging.mtplot_tools.arrows module
Created on Sun Sep 25 15:16:31 2022
@author: jpeacock
- class mtpy.imaging.mtplot_tools.arrows.MTArrows(**kwargs)[source]
Bases:
objectHelper class to configure arrow properties for plotting induction vectors.
This class manages arrow styling parameters for real and imaginary components of induction vectors in magnetotelluric plots.
- Parameters:
**kwargs (dict, optional) – Keyword arguments to set arrow properties. Valid keys correspond to the class attributes listed below.
- arrow_size
Multiplier to scale the arrow size, by default 2.5
- Type:
float
- arrow_head_length
Length of the arrow head, by default 0.15 * arrow_size
- Type:
float
- arrow_head_width
Width of the arrow head, by default 0.1 * arrow_size
- Type:
float
- arrow_lw
Line width of the arrow, by default 0.5 * arrow_size
- Type:
float
- arrow_threshold
Threshold value above which arrows will not be plotted. This helps filter out poor quality data. Applied before scaling by arrow_size, by default 2
- Type:
float
- arrow_color_imag
Color for imaginary component arrows, by default ‘c’ (cyan)
- Type:
str
- arrow_color_real
Color for real component arrows, by default ‘k’ (black)
- Type:
str
- arrow_direction
Arrow direction convention: - 0: arrows point away from conductor - 1: arrows point toward conductor (Parkinson convention) By default 1
- Type:
int
Notes
The data inherently points away from conductors, so arrow_direction=1 flips the arrows to follow the Parkinson convention.
mtpy.imaging.mtplot_tools.base module
Base classes for plotting classes
- author:
jpeacock
- class mtpy.imaging.mtplot_tools.base.PlotBase(**kwargs)[source]
Bases:
PlotSettingsBase class for plotting objects.
Provides core plotting functionality including figure management, saving, updating, and redrawing plots.
- Parameters:
**kwargs (dict) – Keyword arguments passed to PlotSettings parent class
- logger
Logger instance for the class
- Type:
loguru.Logger
- plot() None[source]
Create the plot.
This method should be overridden by subclasses to implement specific plotting functionality.
- redraw_plot() None[source]
Recreate the plot after updating attributes.
Closes the current figure and calls plot() to create a new one with updated attributes.
Examples
>>> # Change the color and marker of the xy components >>> p1.xy_color = (0.5, 0.5, 0.9) >>> p1.xy_marker = '*' >>> p1.redraw_plot()
- save_plot(save_fn: str | Path, file_format: str = 'pdf', orientation: str = 'portrait', fig_dpi: int | None = None, close_plot: bool = True) None[source]
Save the figure to a file.
- Parameters:
save_fn (str | Path) –
Full path to save figure to. Can be: - Directory path: file will be saved as save_fn/basename.file_format - Full path: file will be saved to the given path, format inferred
from extension
file_format (str, optional) – File format for saved figure (pdf, eps, jpg, png, svg), by default ‘pdf’
orientation (str, optional) – Page orientation (‘landscape’ or ‘portrait’), by default ‘portrait’
fig_dpi (int | None, optional) – Resolution in dots-per-inch. If None, uses the figure’s dpi, by default None
close_plot (bool, optional) – Whether to close the plot after saving, by default True
Examples
>>> # Save plot as jpg >>> p1.save_plot(r'/home/MT/figures', file_format='jpg')
- class mtpy.imaging.mtplot_tools.base.PlotBaseMaps(**kwargs)[source]
Bases:
PlotBaseBase object for plot classes that use map views.
Includes methods for interpolation of data onto map grids.
- Parameters:
**kwargs (dict) – Keyword arguments passed to PlotBase parent class and for setting interpolation parameters
- cell_size
Size of grid cells for interpolation, by default 0.002
- Type:
float
- n_padding_cells
Number of padding cells around data extent, by default 10
- Type:
int
- interpolation_method
Interpolation method (‘delaunay’, ‘linear’, ‘nearest’, ‘cubic’), by default ‘delaunay’
- Type:
str
- interpolation_power
Power parameter for inverse distance weighting, by default 5
- Type:
int
- nearest_neighbors
Number of nearest neighbors to use in interpolation, by default 7
- Type:
int
- add_raster(ax, raster_fn: str | Path, add_colorbar: bool = True, **kwargs)[source]
Add a raster image to a matplotlib axis.
- Parameters:
ax (matplotlib.axes.Axes) – Matplotlib axis to add raster to
raster_fn (str | Path) – Path to raster file (readable by rasterio)
add_colorbar (bool, optional) – Whether to add a colorbar, by default True
**kwargs (dict) – Additional keyword arguments passed to rasterio plotting
- Returns:
The raster plot object
- Return type:
matplotlib image or collection
- static get_interp1d_functions_t(tf, interp_type: str = 'slinear') dict | None[source]
Create 1D interpolation functions for tipper components.
- Parameters:
tf (MT or Transfer Function object) – Transfer function object containing tipper data
interp_type (str, optional) – Type of interpolation (‘linear’, ‘slinear’, ‘cubic’), by default ‘slinear’
- Returns:
Dictionary containing interpolation functions for tipper components (tzx, tzy) with ‘real’, ‘imag’, ‘err’, and ‘model_err’ sub-keys. Returns None if no Tipper data available.
- Return type:
dict | None
- static get_interp1d_functions_z(tf, interp_type: str = 'slinear') dict | None[source]
Create 1D interpolation functions for impedance tensor components.
- Parameters:
tf (MT or Transfer Function object) – Transfer function object containing impedance data
interp_type (str, optional) – Type of interpolation (‘linear’, ‘slinear’, ‘cubic’), by default ‘slinear’
- Returns:
Dictionary containing interpolation functions for each impedance component (zxx, zxy, zyx, zyy) with ‘real’, ‘imag’, ‘err’, and ‘model_err’ sub-keys. Returns None if no Z data available.
- Return type:
dict | None
- interpolate_to_map(plot_array, component: str)[source]
Interpolate data points onto a 2D map grid.
- Parameters:
plot_array (np.ndarray) – Array containing data to interpolate
component (str) – Name of the component being interpolated
- Returns:
Interpolated grid data and coordinates
- Return type:
tuple
- class mtpy.imaging.mtplot_tools.base.PlotBaseProfile(tf_list, **kwargs)[source]
Bases:
PlotBaseBase object for profile plots like pseudo sections.
Provides functionality for creating profile views of MT data along a linear transect.
- Parameters:
tf_list (list or MTCollection) – List of transfer function objects or MTCollection
**kwargs (dict) – Additional keyword arguments for PlotBase parent class and profile settings
- mt_data
MT data to plot
- Type:
list or MTCollection
- profile_vector
Profile direction vector
- Type:
array-like | None
- profile_angle
Profile angle in degrees
- Type:
float | None
- profile_line
Profile line parameters (slope, intercept)
- Type:
tuple | None
- profile_reverse
Whether to reverse profile direction, by default False
- Type:
bool
- x_stretch
Horizontal stretching factor for profile, by default 5000
- Type:
float
- y_stretch
Vertical stretching factor for profile, by default 1000
- Type:
float
- y_scale
Y-axis scale type (‘period’ or ‘frequency’), by default ‘period’
- Type:
str
- property rotation_angle: float
Get rotation angle for data.
- Returns:
Rotation angle in degrees
- Return type:
float
mtpy.imaging.mtplot_tools.ellipses module
Created on Sun Sep 25 15:19:16 2022
@author: jpeacock
- class mtpy.imaging.mtplot_tools.ellipses.MTEllipse(**kwargs)[source]
Bases:
objectHelper class for managing phase tensor ellipse properties.
Configures ellipse visualization parameters including size, color mapping, and color ranges for plotting phase tensor ellipses.
- Parameters:
**kwargs (dict, optional) – Keyword arguments to set ellipse properties. Valid keys correspond to the class attributes listed below.
- ellipse_size
Size of ellipse in points, by default 2
- Type:
float
- ellipse_colorby
Property to color ellipses by: - ‘phimin’ or ‘phiminang’: minimum phase (default) - ‘phimax’ or ‘phimaxang’: maximum phase - ‘skew’: skew angle (beta) - ‘skew_seg’: skew in discrete segments - ‘normalized_skew’: normalized skew (Booker, 2014) - ‘normalized_skew_seg’: normalized skew in discrete segments - ‘phidet’: determinant of phase tensor - ‘ellipticity’: ellipticity of phase tensor - ‘strike’ or ‘azimuth’: strike angle
- Type:
str
- ellipse_range
Range for color mapping as (min, max, step), by default (0, 90, 10)
- Type:
tuple[float, float, float]
- ellipse_cmap
Colormap name: - ‘mt_yl2rd’: yellow to red - ‘mt_bl2yl2rd’: blue to yellow to red - ‘mt_wh2bl’: white to blue - ‘mt_rd2bl’: red to blue - ‘mt_bl2wh2rd’: blue to white to red - ‘mt_bl2gr2rd’: blue to green to red (default) - ‘mt_rd2gr2bl’: red to green to blue - ‘mt_seg_bl2wh2rd’: discrete blue to white to red
- Type:
str
- ellipse_spacing
Spacing between ellipses, by default 1
- Type:
float
- property ellipse_cmap_bounds: ndarray | None
Get colormap boundaries for discrete coloring.
- Returns:
Array of boundary values for colormap bins, or None if ellipse_range is not properly defined
- Return type:
np.ndarray | None
- property ellipse_cmap_n_segments: float
Calculate number of segments for colormap.
- Returns:
Number of colormap segments based on ellipse_range
- Return type:
float
- property ellipse_properties: dict[str, float | tuple | str]
Get dictionary of ellipse properties.
- Returns:
Dictionary containing ellipse visualization parameters: - size: ellipse size - range: color range tuple - cmap: colormap name - colorby: property to color by - spacing: ellipse spacing
- Return type:
dict[str, float | tuple | str]
- get_color_map() None[source]
Set appropriate colormap based on colorby property.
Automatically sets colormap to ‘mt_seg_bl2wh2rd’ for segmented skew coloring modes.
- get_pt_color_array(pt_object) ndarray[source]
Extract appropriate array from phase tensor for coloring ellipses.
- Parameters:
pt_object (PhaseTensor) – Phase tensor object containing phase tensor properties
- Returns:
Array of values corresponding to the selected colorby property
- Return type:
np.ndarray
- Raises:
NameError – If ellipse_colorby is not a supported option
mtpy.imaging.mtplot_tools.map_interpolation_tools module
Created on Sun Sep 25 15:06:58 2022
@author: jpeacock
- mtpy.imaging.mtplot_tools.map_interpolation_tools.get_plot_xy(plot_array: ndarray, cell_size: float, n_padding_cells: int) tuple[ndarray, ndarray][source]
Generate uniform x and y coordinates for interpolation grid.
Creates regular grid coordinates with padding around the data extent.
- Parameters:
plot_array (np.ndarray) – Structured array with ‘longitude’ and ‘latitude’ fields
cell_size (float) – Size of grid cells in decimal degrees
n_padding_cells (int) – Number of padding cells to add around data extent
- Returns:
plot_x : 1D array of x (longitude) coordinates plot_y : 1D array of y (latitude) coordinates
- Return type:
tuple[np.ndarray, np.ndarray]
- mtpy.imaging.mtplot_tools.map_interpolation_tools.griddata_interpolate(x: ndarray, y: ndarray, values: ndarray, new_x: ndarray, new_y: ndarray, interpolation_method: str = 'cubic') tuple[ndarray, ndarray, ndarray][source]
Interpolate scattered data to regular grid using scipy.interpolate.griddata.
- Parameters:
x (np.ndarray) – X coordinates of data points
y (np.ndarray) – Y coordinates of data points
values (np.ndarray) – Values at data points
new_x (np.ndarray) – Target x coordinates for interpolation
new_y (np.ndarray) – Target y coordinates for interpolation
interpolation_method (str, optional) – Interpolation method: ‘nearest’, ‘linear’, or ‘cubic’, by default ‘cubic’
- Returns:
grid_x : 2D array of x coordinates grid_y : 2D array of y coordinates image : 2D array of interpolated values
- Return type:
tuple[np.ndarray, np.ndarray, np.ndarray]
- mtpy.imaging.mtplot_tools.map_interpolation_tools.in_hull(p: ndarray, hull: ndarray | Delaunay) ndarray[source]
Test if points are within a convex hull.
Uses Delaunay triangulation for efficient point-in-hull testing. Falls back to linear programming for collinear point configurations.
- Parameters:
p (np.ndarray) – Points to test, shape (n_points, n_dimensions)
hull (np.ndarray | Delaunay) – Either array of hull vertices or pre-computed Delaunay object
- Returns:
Boolean array indicating which points are inside the hull
- Return type:
np.ndarray
- mtpy.imaging.mtplot_tools.map_interpolation_tools.interpolate_to_map(plot_array: ndarray, component: str, cell_size: float = 0.002, n_padding_cells: int = 10, interpolation_method: str = 'delaunay', interpolation_power: float = 5, nearest_neighbors: int = 7) tuple[ndarray | Triangulation, ndarray, ndarray | None][source]
Interpolate MT data to regular map grid.
Dispatcher function that selects appropriate interpolation method. Supports both griddata-based (nearest, linear, cubic) and triangulation-based (delaunay, fancy) methods.
- Parameters:
plot_array (np.ndarray) – Structured array with ‘longitude’, ‘latitude’, and component fields
component (str) – Name of component to interpolate (e.g., ‘res_xy’, ‘phase_xy’)
cell_size (float, optional) – Size of grid cells in decimal degrees, by default 0.002
n_padding_cells (int, optional) – Number of padding cells around data extent, by default 10
interpolation_method (str, optional) – Interpolation method: - ‘nearest’, ‘linear’, ‘cubic’: scipy.interpolate.griddata methods - ‘delaunay’, ‘fancy’, ‘triangulate’: triangulation with IDW by default ‘delaunay’
interpolation_power (float, optional) – Power parameter for IDW in triangulation methods, by default 5
nearest_neighbors (int, optional) – Number of nearest neighbors for IDW, by default 7
- Returns:
grid_x or triangulation : Grid x coordinates (2D) or triangulation object grid_y or image : Grid y coordinates (2D) or interpolated values image or inside_indices : Interpolated values or boolean hull mask
- Return type:
tuple[np.ndarray | tri.Triangulation, np.ndarray, np.ndarray | None]
Notes
Return types differ by method: - griddata methods: (grid_x, grid_y, image) - triangulation methods: (triangulation, image, inside_indices)
- mtpy.imaging.mtplot_tools.map_interpolation_tools.interpolate_to_map_griddata(plot_array: ndarray, component: str, cell_size: float = 0.002, n_padding_cells: int = 10, interpolation_method: str = 'cubic') tuple[ndarray, ndarray, ndarray][source]
Interpolate MT data to regular map grid using griddata method.
- Parameters:
plot_array (np.ndarray) – Structured array with ‘longitude’, ‘latitude’, and component fields
component (str) – Name of component to interpolate (e.g., ‘res_xy’, ‘phase_xy’)
cell_size (float, optional) – Size of grid cells in decimal degrees, by default 0.002
n_padding_cells (int, optional) – Number of padding cells around data extent, by default 10
interpolation_method (str, optional) – Interpolation method: ‘nearest’, ‘linear’, or ‘cubic’, by default ‘cubic’
- Returns:
grid_x : 2D array of x (longitude) coordinates grid_y : 2D array of y (latitude) coordinates image : 2D array of interpolated values (log10 for resistivity)
- Return type:
tuple[np.ndarray, np.ndarray, np.ndarray]
- mtpy.imaging.mtplot_tools.map_interpolation_tools.interpolate_to_map_triangulate(plot_array: ndarray, component: str, cell_size: float = 0.002, n_padding_cells: int = 10, nearest_neighbors: int = 7, interp_pow: float = 4) tuple[Triangulation, ndarray, ndarray][source]
Interpolate MT data to map using Delaunay triangulation method.
Uses triangulation with inverse distance weighting (IDW) for interpolation. Automatically applies log10 transform to resistivity components.
- Parameters:
plot_array (np.ndarray) – Structured array with required fields: - ‘latitude’: latitude in decimal degrees - ‘longitude’: longitude in decimal degrees - component field (e.g., ‘res_xy’, ‘phase_xy’)
component (str) – Name of component to interpolate (must be field in plot_array)
cell_size (float, optional) – Size of grid cells in decimal degrees, by default 0.002
n_padding_cells (int, optional) – Number of padding cells around data extent, by default 10
nearest_neighbors (int, optional) – Number of nearest neighbors for IDW interpolation, by default 7
interp_pow (float, optional) – Power parameter for IDW interpolation, by default 4
- Returns:
triangulation : Matplotlib triangulation object with mask image : Flattened array of interpolated values (log10 for resistivity) inside_indices : Boolean array indicating triangles inside hull
- Return type:
tuple[tri.Triangulation, np.ndarray, np.ndarray]
- mtpy.imaging.mtplot_tools.map_interpolation_tools.triangulate_interpolation(x: ndarray, y: ndarray, values: ndarray, padded_x: ndarray, padded_y: ndarray, new_x: ndarray, new_y: ndarray, nearest_neighbors: int = 7, interp_pow: float = 4) tuple[Triangulation, ndarray, ndarray][source]
Interpolate using Delaunay triangulation and inverse distance weighting.
Creates triangulation on target grid and uses IDW interpolation with k-nearest neighbors from source data points. Masks triangles outside the convex hull.
- Parameters:
x (np.ndarray) – X coordinates of source data points
y (np.ndarray) – Y coordinates of source data points
values (np.ndarray) – Values at source data points
padded_x (np.ndarray) – Padded x coordinates defining convex hull boundary
padded_y (np.ndarray) – Padded y coordinates defining convex hull boundary
new_x (np.ndarray) – Target x coordinates for interpolation
new_y (np.ndarray) – Target y coordinates for interpolation
nearest_neighbors (int, optional) – Number of nearest neighbors for IDW interpolation, by default 7
interp_pow (float, optional) – Power parameter for IDW (higher = more weight to closer points), by default 4
- Returns:
triangulation : Matplotlib triangulation object with mask image : Flattened array of interpolated values inside_indices : Boolean array indicating triangles inside hull
- Return type:
tuple[tri.Triangulation, np.ndarray, np.ndarray]
mtpy.imaging.mtplot_tools.plot_settings module
Created on Sun Sep 25 15:20:43 2022
@author: jpeacock
- class mtpy.imaging.mtplot_tools.plot_settings.PlotSettings(**kwargs)[source]
-
Comprehensive plot settings for MT data visualization.
Combines arrow and ellipse settings with figure, marker, line, and colorbar properties for creating publication-quality MT plots.
- Parameters:
**kwargs (dict, optional) – Keyword arguments to set any class attributes. Valid keys correspond to the extensive list of attributes below.
- fig_num
Figure number, by default 1
- Type:
int
- fig_dpi
Figure DPI resolution, by default 150
- Type:
int
- fig_size
Figure size (width, height) in inches, by default None
- Type:
tuple | None
- show_plot
Whether to display plot, by default True
- Type:
bool
- font_size
Base font size for plot text, by default 7
- Type:
int
- font_weight
Font weight (‘normal’, ‘bold’, etc.), by default ‘bold’
- Type:
str
- marker_size
Size of plot markers, by default 2.5
- Type:
float
- marker_lw
Line width of marker edges, by default 0.75
- Type:
float
- marker_color
Default marker color, by default ‘b’
- Type:
str
- marker
Default marker style, by default ‘v’
- Type:
str
- lw
Default line width, by default 1
- Type:
float
- plot_title
Plot title text, by default None
- Type:
str | None
- xy_ls, yx_ls, det_ls, skew_ls, strike_ls
Line styles for different components, by default ‘:’
- Type:
str
- xy_marker, yx_marker, det_marker, skew_marker
Marker styles for different components
- Type:
str
- strike_inv_marker, strike_pt_marker, strike_tip_marker
Marker styles for strike indicators
- Type:
str
- xy_color, yx_color, det_color, skew_color
RGB colors for different components
- Type:
tuple
- strike_inv_color, strike_pt_color, strike_tip_color
RGB colors for strike indicators
- Type:
tuple
- x_limits, y_limits, res_limits, phase_limits
Axis limits for various plot types
- Type:
tuple | None
- tipper_limits, strike_limits, skew_limits, pt_limits
Additional axis limits
- Type:
tuple | None
- plot_z
Whether to plot impedance, by default True
- Type:
bool
- plot_tipper
Tipper plotting mode (‘n’, ‘y’, ‘yri’), by default ‘n’
- Type:
str
- plot_pt
Whether to plot phase tensor, by default False
- Type:
bool
- plot_strike
Whether to plot strike, by default False
- Type:
bool
- plot_skew
Whether to plot skew, by default False
- Type:
bool
- text_size
Text annotation size, by default 7
- Type:
int
- text_weight
Text annotation weight, by default ‘normal’
- Type:
str
- text_color
Text annotation color, by default ‘k’
- Type:
str
- text_ha
Text horizontal alignment, by default ‘center’
- Type:
str
- text_va
Text vertical alignment, by default ‘baseline’
- Type:
str
- text_angle
Text rotation angle, by default 0
- Type:
float
- text_x_pad, text_y_pad
Text padding in x/y directions, by default 0
- Type:
float
- text_rotation
Additional text rotation, by default 0
- Type:
float
- subplot_left, subplot_right, subplot_bottom, subplot_top
Subplot spacing parameters
- Type:
float
- subplot_wspace, subplot_hspace
Width/height spacing between subplots
- Type:
float | None
- cb_orientation
Colorbar orientation (‘vertical’ or ‘horizontal’), by default ‘vertical’
- Type:
str
- cb_position
Colorbar position [left, bottom, width, height], by default None
- Type:
tuple | None
- property arrow_imag_properties: dict[str, str | float | bool]
Get matplotlib arrow properties for imaginary tipper component.
- Returns:
Dictionary of arrow kwargs including line width, colors, head dimensions, and length settings
- Return type:
dict[str, str | float | bool]
- property arrow_real_properties: dict[str, str | float | bool]
Get matplotlib arrow properties for real tipper component.
- Returns:
Dictionary of arrow kwargs including line width, colors, head dimensions, and length settings
- Return type:
dict[str, str | float | bool]
- property det_error_bar_properties: dict[str, str | float]
Get matplotlib errorbar properties for determinant component.
- Returns:
Dictionary of errorbar kwargs including marker style, size, colors, line styles, and cap properties
- Return type:
dict[str, str | float]
- property font_dict: dict[str, int | str]
Get font properties dictionary for matplotlib.
Adjusts key names based on matplotlib version for compatibility.
- Returns:
Font properties with ‘size’/’fontsize’ and ‘weight’/’fontweight’ depending on matplotlib version
- Return type:
dict[str, int | str]
- make_pt_cb(ax: Axes) mcb.Colorbar[source]
Create phase tensor colorbar.
Generates colorbar for phase tensor plots with appropriate color mapping, normalization, and labeling based on ellipse settings.
- Parameters:
ax (Axes) – Matplotlib axes to attach colorbar to
- Returns:
Configured matplotlib colorbar object
- Return type:
mcb.Colorbar
- property period_label_dict: dict[int, str]
Get LaTeX-formatted period labels for log10 scale.
- Returns:
Dictionary mapping integer exponents to LaTeX strings in format $10^{exponent}$ for range -20 to 20
- Return type:
dict[int, str]
- set_period_limits(period: ndarray) tuple[float, float][source]
Calculate period axis limits as powers of 10.
- Parameters:
period (np.ndarray) – Array of period values
- Returns:
Minimum and maximum limits as powers of 10 (floor and ceil)
- Return type:
tuple[float, float]
- set_phase_limits(phase: ndarray, mode: str = 'od') tuple[float, float] | list[float][source]
Calculate appropriate phase axis limits.
- Parameters:
phase (np.ndarray) – Phase array with shape (n_periods, 2, 2) for full tensor or (n_periods,) for determinant
mode (str, optional) – Plotting mode: - ‘od’: off-diagonal components (0-90 range with adjustments) - ‘d’: diagonal components (-180 to 180) - ‘det’ or ‘det_only’: determinant phase by default ‘od’
- Returns:
[min_limit, max_limit] in degrees Defaults to [0, 90] for ‘od’ or [-180, 180] for others if calculation fails
- Return type:
tuple[float, float] | list[float]
- set_resistivity_limits(resistivity: ndarray, mode: str = 'od', scale: str = 'log') list[float][source]
Calculate appropriate resistivity axis limits.
- Parameters:
resistivity (np.ndarray) – Resistivity array with shape (n_periods, 2, 2) for full tensor or (n_periods,) for determinant
mode (str, optional) – Plotting mode: - ‘od’: off-diagonal components (xy, yx) - ‘d’: diagonal components (xx, yy) - ‘det’ or ‘det_only’: determinant only - ‘all’: all components by default ‘od’
scale (str, optional) – Scale type (‘log’ or ‘linear’), by default ‘log’
- Returns:
[min_limit, max_limit] as powers of 10 Defaults to [0.1, 10000] if calculation fails
- Return type:
list[float]
- property text_dict: dict[str, int | str | float]
Get text annotation properties dictionary.
- Returns:
Dictionary of text properties including size, weight, rotation angle, and color
- Return type:
dict[str, int | str | float]
- property xy_error_bar_properties: dict[str, str | float]
Get matplotlib errorbar properties for xy component.
- Returns:
Dictionary of errorbar kwargs including marker style, size, colors, line styles, and cap properties
- Return type:
dict[str, str | float]
- property yx_error_bar_properties: dict[str, str | float]
Get matplotlib errorbar properties for yx component.
- Returns:
Dictionary of errorbar kwargs including marker style, size, colors, line styles, and cap properties
- Return type:
dict[str, str | float]
mtpy.imaging.mtplot_tools.plotters module
Simple plotters elements that can be assembled in various plotting classes
Created on Sun Sep 25 15:27:28 2022
- author:
jpeacock
- mtpy.imaging.mtplot_tools.plotters.add_raster(ax: Axes, raster_fn: str, add_colorbar: bool = True, **kwargs) tuple[Axes, mcb.Colorbar | None][source]
Add a raster image to axes using rasterio.
Overlays a georeferenced raster (e.g., GeoTIFF) on matplotlib axes with optional colorbar.
- Parameters:
ax (Axes) – Matplotlib axes to add raster to
raster_fn (str) – Path to raster file (must be readable by rasterio)
add_colorbar (bool, optional) – Whether to add colorbar, by default True
**kwargs (dict, optional) – Additional keyword arguments passed to rasterio.plot.show
- Returns:
Updated axes and colorbar (None if add_colorbar=False)
- Return type:
tuple[Axes, mcb.Colorbar | None]
- mtpy.imaging.mtplot_tools.plotters.plot_errorbar(ax: Axes, x_array: np.ndarray, y_array: np.ndarray, y_error: np.ndarray | None = None, x_error: np.ndarray | None = None, **kwargs) ErrorbarContainer[source]
Create error bar plot with customizable properties.
Convenience function to generate matplotlib errorbar plots with sensible defaults that can be overridden via kwargs.
- Parameters:
ax (Axes) – Matplotlib axes to plot on
x_array (np.ndarray) – Array of x values
y_array (np.ndarray) – Array of y values
y_error (np.ndarray | None, optional) – Array of y-direction error values, by default None
x_error (np.ndarray | None, optional) – Array of x-direction error values, by default None
**kwargs (dict, optional) – Additional errorbar properties: - color : marker, line, and error bar color - marker : marker style - mew : marker edge width - mec : marker edge color - ms : marker size - ls : line style - lw : line width - capsize : error bar cap size - capthick : error bar cap thickness - ecolor : error bar color - elinewidth : error bar line width - picker : pick radius in points
- Returns:
Matplotlib errorbar container with line data and error bars
- Return type:
ErrorbarContainer
- mtpy.imaging.mtplot_tools.plotters.plot_phase(ax: Axes, period: np.ndarray, phase: np.ndarray | None, error: np.ndarray | None, yx: bool = False, **properties) list[ErrorbarContainer | None][source]
Plot phase with error bars.
Plots only non-zero phase values. Optionally adds 180 degrees to yx component for proper quadrant representation.
- Parameters:
ax (Axes) – Matplotlib axes to plot on
period (np.ndarray) – Array of period values
phase (np.ndarray | None) – Array of phase values (degrees)
error (np.ndarray | None) – Array of phase error values
yx (bool, optional) – If True, adds 180 degrees to phase for yx component, by default False
**properties (dict, optional) – Additional errorbar properties passed to plot_errorbar
- Returns:
List containing errorbar container or [None] if no data
- Return type:
list[ErrorbarContainer | None]
- mtpy.imaging.mtplot_tools.plotters.plot_pt_lateral(ax: Axes, pt_obj, color_array: np.ndarray, ellipse_properties: dict, y_shift: float = 0, fig: Figure | None = None, edge_color: str | tuple | None = None, n_index: int = 0) tuple[Axes | None, mcb.Colorbar | None][source]
Plot phase tensor ellipses on lateral (period) axis.
Creates phase tensor ellipse plot with ellipses scaled by phimin/phimax and oriented by azimuth. Includes optional colorbar.
- Parameters:
ax (Axes) – Matplotlib axes to plot on
pt_obj (PhaseTensor) – Phase tensor object with frequency, phimin, phimax, and azimuth
color_array (np.ndarray) – Array of values for coloring ellipses
ellipse_properties (dict) – Dictionary with keys: - ‘size’: ellipse size scaling factor - ‘spacing’: spacing between ellipses on period axis - ‘colorby’: property to color by - ‘cmap’: colormap name - ‘range’: [min, max, step] for color mapping
y_shift (float, optional) – Vertical offset for ellipse centers, by default 0
fig (Figure | None, optional) – Figure for adding colorbar, by default None
edge_color (str | tuple | None, optional) – Color for ellipse edges, by default None
n_index (int, optional) – Index for controlling colorbar creation (only at 0), by default 0
- Returns:
Colorbar axes and colorbar object (both None if n_index != 0)
- Return type:
tuple[Axes | None, mcb.Colorbar | None]
- mtpy.imaging.mtplot_tools.plotters.plot_resistivity(ax: Axes, period: np.ndarray, resistivity: np.ndarray | None, error: np.ndarray | None, **properties) list[ErrorbarContainer | None][source]
Plot apparent resistivity with error bars.
Plots only non-zero resistivity values on the given axes.
- Parameters:
ax (Axes) – Matplotlib axes to plot on
period (np.ndarray) – Array of period values
resistivity (np.ndarray | None) – Array of apparent resistivity values (ohm-m)
error (np.ndarray | None) – Array of resistivity error values
**properties (dict, optional) – Additional errorbar properties passed to plot_errorbar
- Returns:
List containing errorbar container or [None] if no data
- Return type:
list[ErrorbarContainer | None]
- mtpy.imaging.mtplot_tools.plotters.plot_tipper_lateral(axt: Axes | None, t_obj, plot_tipper: str | bool, real_properties: dict, imag_properties: dict, font_size: int = 6, legend: bool = True, zero_reference: bool = False, arrow_direction: int = 1) tuple[Axes | None, list[Line2D] | None, list[str] | None][source]
Plot tipper arrows on lateral (period) axis.
Creates tipper arrow plot showing real and/or imaginary components as arrows with magnitude and direction.
- Parameters:
axt (Axes | None) – Matplotlib axes to plot on (returns None if None)
t_obj (Tipper) – Tipper object with frequency, mag_real, angle_real, mag_imag, and angle_imag attributes
plot_tipper (str | bool) – Tipper plotting mode: - ‘yri’: plot both real and imaginary - ‘yr’: plot real only - ‘yi’: plot imaginary only - ‘y’: plot both - False/None: no plot
real_properties (dict) – Arrow properties for real component (matplotlib arrow kwargs)
imag_properties (dict) – Arrow properties for imaginary component (matplotlib arrow kwargs)
font_size (int, optional) – Font size for axis labels and legend, by default 6
legend (bool, optional) – Whether to show legend, by default True
zero_reference (bool, optional) – Whether to plot zero reference line, by default False
arrow_direction (int, optional) – Arrow direction multiplier (1 or -1), by default 1
- Returns:
Updated axes, legend handles list, and legend labels list All None if axt is None or t_obj is None
- Return type:
tuple[Axes | None, list[Line2D] | None, list[str] | None]
mtpy.imaging.mtplot_tools.utils module
Utility functions for plotting
Created on Sun Sep 25 15:49:01 2022
- author:
jpeacock
- mtpy.imaging.mtplot_tools.utils.add_colorbar_axis(ax: Axes, fig: Figure) Axes[source]
Add colorbar axes positioned to the left of given axes.
Creates a new axes for colorbar placement with dimensions calculated relative to the input axes position.
- Parameters:
ax (Axes) – Reference axes for positioning colorbar
fig (Figure) – Figure to add colorbar axes to
- Returns:
New axes object for colorbar
- Return type:
Axes
- mtpy.imaging.mtplot_tools.utils.get_log_tick_labels(ax: Axes, spacing: float = 1) tuple[list[str], list[float]][source]
Get LaTeX-formatted tick labels for logarithmic period axis.
Generates tick labels in format $10^{exponent}$ for valid tick positions.
- Parameters:
ax (Axes) – Axes to extract tick positions from
spacing (float, optional) – Spacing factor for tick positions, by default 1
- Returns:
Tick labels (LaTeX strings) and corresponding tick positions
- Return type:
tuple[list[str], list[float]]
- mtpy.imaging.mtplot_tools.utils.get_period_limits(period: ndarray) tuple[float, float][source]
Calculate period axis limits as powers of 10.
- Parameters:
period (np.ndarray) – Array of period values
- Returns:
Minimum and maximum limits as powers of 10 (floor and ceil)
- Return type:
tuple[float, float]
- mtpy.imaging.mtplot_tools.utils.make_color_list(cbax: Axes, nseg: float, ckmin: float, ckmax: float, ckstep: float) mcb.ColorbarBase[source]
Create segmented blue-white-red colorbar.
Generates a colorbar with blue-to-white-to-red color transition using discrete segments with specified bounds.
- Parameters:
cbax (Axes) – Axes to place colorbar in
nseg (float) – Number of color segments
ckmin (float) – Minimum value for colorbar range
ckmax (float) – Maximum value for colorbar range
ckstep (float) – Step size between color boundaries
- Returns:
Colorbar object with segmented colormap
- Return type:
mcb.ColorbarBase
- mtpy.imaging.mtplot_tools.utils.make_value_str(value: float, value_list: str | list[str] | None = None, spacing: str = '{0:^8}', value_format: str = '{0: .2f}', append: bool = False, add: bool = False) list[str] | str[source]
Format value as string for file output.
Helper function for writing values to file. Converts value to formatted string and either appends to list, concatenates to string, or returns standalone string.
- Parameters:
value (float) – Numeric value to format
value_list (list[str] | str | None, optional) – Existing list or string to modify, by default None
spacing (str, optional) – Format string for spacing (e.g., ‘{0:^8}’), by default ‘{0:^8}’
value_format (str, optional) – Format string for value (e.g., ‘{0: .2f}’), by default ‘{0: .2f}’
append (bool, optional) – If True, append to value_list (must be list), by default False
add (bool, optional) – If True, concatenate to value_list (must be str), by default False
- Returns:
Modified list/string or standalone formatted string
- Return type:
list[str] | str
Notes
If both append and add are False, returns formatted string. If append is True, appends to list and returns list. If add is True, concatenates to string and returns string.
Module contents
- class mtpy.imaging.mtplot_tools.MTArrows(**kwargs)[source]
Bases:
objectHelper class to configure arrow properties for plotting induction vectors.
This class manages arrow styling parameters for real and imaginary components of induction vectors in magnetotelluric plots.
- Parameters:
**kwargs (dict, optional) – Keyword arguments to set arrow properties. Valid keys correspond to the class attributes listed below.
- arrow_size
Multiplier to scale the arrow size, by default 2.5
- Type:
float
- arrow_head_length
Length of the arrow head, by default 0.15 * arrow_size
- Type:
float
- arrow_head_width
Width of the arrow head, by default 0.1 * arrow_size
- Type:
float
- arrow_lw
Line width of the arrow, by default 0.5 * arrow_size
- Type:
float
- arrow_threshold
Threshold value above which arrows will not be plotted. This helps filter out poor quality data. Applied before scaling by arrow_size, by default 2
- Type:
float
- arrow_color_imag
Color for imaginary component arrows, by default ‘c’ (cyan)
- Type:
str
- arrow_color_real
Color for real component arrows, by default ‘k’ (black)
- Type:
str
- arrow_direction
Arrow direction convention: - 0: arrows point away from conductor - 1: arrows point toward conductor (Parkinson convention) By default 1
- Type:
int
Notes
The data inherently points away from conductors, so arrow_direction=1 flips the arrows to follow the Parkinson convention.
- class mtpy.imaging.mtplot_tools.MTEllipse(**kwargs)[source]
Bases:
objectHelper class for managing phase tensor ellipse properties.
Configures ellipse visualization parameters including size, color mapping, and color ranges for plotting phase tensor ellipses.
- Parameters:
**kwargs (dict, optional) – Keyword arguments to set ellipse properties. Valid keys correspond to the class attributes listed below.
- ellipse_size
Size of ellipse in points, by default 2
- Type:
float
- ellipse_colorby
Property to color ellipses by: - ‘phimin’ or ‘phiminang’: minimum phase (default) - ‘phimax’ or ‘phimaxang’: maximum phase - ‘skew’: skew angle (beta) - ‘skew_seg’: skew in discrete segments - ‘normalized_skew’: normalized skew (Booker, 2014) - ‘normalized_skew_seg’: normalized skew in discrete segments - ‘phidet’: determinant of phase tensor - ‘ellipticity’: ellipticity of phase tensor - ‘strike’ or ‘azimuth’: strike angle
- Type:
str
- ellipse_range
Range for color mapping as (min, max, step), by default (0, 90, 10)
- Type:
tuple[float, float, float]
- ellipse_cmap
Colormap name: - ‘mt_yl2rd’: yellow to red - ‘mt_bl2yl2rd’: blue to yellow to red - ‘mt_wh2bl’: white to blue - ‘mt_rd2bl’: red to blue - ‘mt_bl2wh2rd’: blue to white to red - ‘mt_bl2gr2rd’: blue to green to red (default) - ‘mt_rd2gr2bl’: red to green to blue - ‘mt_seg_bl2wh2rd’: discrete blue to white to red
- Type:
str
- ellipse_spacing
Spacing between ellipses, by default 1
- Type:
float
- property ellipse_cmap_bounds: ndarray | None
Get colormap boundaries for discrete coloring.
- Returns:
Array of boundary values for colormap bins, or None if ellipse_range is not properly defined
- Return type:
np.ndarray | None
- property ellipse_cmap_n_segments: float
Calculate number of segments for colormap.
- Returns:
Number of colormap segments based on ellipse_range
- Return type:
float
- property ellipse_properties: dict[str, float | tuple | str]
Get dictionary of ellipse properties.
- Returns:
Dictionary containing ellipse visualization parameters: - size: ellipse size - range: color range tuple - cmap: colormap name - colorby: property to color by - spacing: ellipse spacing
- Return type:
dict[str, float | tuple | str]
- get_color_map() None[source]
Set appropriate colormap based on colorby property.
Automatically sets colormap to ‘mt_seg_bl2wh2rd’ for segmented skew coloring modes.
- get_pt_color_array(pt_object) ndarray[source]
Extract appropriate array from phase tensor for coloring ellipses.
- Parameters:
pt_object (PhaseTensor) – Phase tensor object containing phase tensor properties
- Returns:
Array of values corresponding to the selected colorby property
- Return type:
np.ndarray
- Raises:
NameError – If ellipse_colorby is not a supported option
- class mtpy.imaging.mtplot_tools.PlotBase(**kwargs)[source]
Bases:
PlotSettingsBase class for plotting objects.
Provides core plotting functionality including figure management, saving, updating, and redrawing plots.
- Parameters:
**kwargs (dict) – Keyword arguments passed to PlotSettings parent class
- logger
Logger instance for the class
- Type:
loguru.Logger
- plot() None[source]
Create the plot.
This method should be overridden by subclasses to implement specific plotting functionality.
- redraw_plot() None[source]
Recreate the plot after updating attributes.
Closes the current figure and calls plot() to create a new one with updated attributes.
Examples
>>> # Change the color and marker of the xy components >>> p1.xy_color = (0.5, 0.5, 0.9) >>> p1.xy_marker = '*' >>> p1.redraw_plot()
- save_plot(save_fn: str | Path, file_format: str = 'pdf', orientation: str = 'portrait', fig_dpi: int | None = None, close_plot: bool = True) None[source]
Save the figure to a file.
- Parameters:
save_fn (str | Path) –
Full path to save figure to. Can be: - Directory path: file will be saved as save_fn/basename.file_format - Full path: file will be saved to the given path, format inferred
from extension
file_format (str, optional) – File format for saved figure (pdf, eps, jpg, png, svg), by default ‘pdf’
orientation (str, optional) – Page orientation (‘landscape’ or ‘portrait’), by default ‘portrait’
fig_dpi (int | None, optional) – Resolution in dots-per-inch. If None, uses the figure’s dpi, by default None
close_plot (bool, optional) – Whether to close the plot after saving, by default True
Examples
>>> # Save plot as jpg >>> p1.save_plot(r'/home/MT/figures', file_format='jpg')
- class mtpy.imaging.mtplot_tools.PlotBaseMaps(**kwargs)[source]
Bases:
PlotBaseBase object for plot classes that use map views.
Includes methods for interpolation of data onto map grids.
- Parameters:
**kwargs (dict) – Keyword arguments passed to PlotBase parent class and for setting interpolation parameters
- cell_size
Size of grid cells for interpolation, by default 0.002
- Type:
float
- n_padding_cells
Number of padding cells around data extent, by default 10
- Type:
int
- interpolation_method
Interpolation method (‘delaunay’, ‘linear’, ‘nearest’, ‘cubic’), by default ‘delaunay’
- Type:
str
- interpolation_power
Power parameter for inverse distance weighting, by default 5
- Type:
int
- nearest_neighbors
Number of nearest neighbors to use in interpolation, by default 7
- Type:
int
- add_raster(ax, raster_fn: str | Path, add_colorbar: bool = True, **kwargs)[source]
Add a raster image to a matplotlib axis.
- Parameters:
ax (matplotlib.axes.Axes) – Matplotlib axis to add raster to
raster_fn (str | Path) – Path to raster file (readable by rasterio)
add_colorbar (bool, optional) – Whether to add a colorbar, by default True
**kwargs (dict) – Additional keyword arguments passed to rasterio plotting
- Returns:
The raster plot object
- Return type:
matplotlib image or collection
- static get_interp1d_functions_t(tf, interp_type: str = 'slinear') dict | None[source]
Create 1D interpolation functions for tipper components.
- Parameters:
tf (MT or Transfer Function object) – Transfer function object containing tipper data
interp_type (str, optional) – Type of interpolation (‘linear’, ‘slinear’, ‘cubic’), by default ‘slinear’
- Returns:
Dictionary containing interpolation functions for tipper components (tzx, tzy) with ‘real’, ‘imag’, ‘err’, and ‘model_err’ sub-keys. Returns None if no Tipper data available.
- Return type:
dict | None
- static get_interp1d_functions_z(tf, interp_type: str = 'slinear') dict | None[source]
Create 1D interpolation functions for impedance tensor components.
- Parameters:
tf (MT or Transfer Function object) – Transfer function object containing impedance data
interp_type (str, optional) – Type of interpolation (‘linear’, ‘slinear’, ‘cubic’), by default ‘slinear’
- Returns:
Dictionary containing interpolation functions for each impedance component (zxx, zxy, zyx, zyy) with ‘real’, ‘imag’, ‘err’, and ‘model_err’ sub-keys. Returns None if no Z data available.
- Return type:
dict | None
- interpolate_to_map(plot_array, component: str)[source]
Interpolate data points onto a 2D map grid.
- Parameters:
plot_array (np.ndarray) – Array containing data to interpolate
component (str) – Name of the component being interpolated
- Returns:
Interpolated grid data and coordinates
- Return type:
tuple
- class mtpy.imaging.mtplot_tools.PlotBaseProfile(tf_list, **kwargs)[source]
Bases:
PlotBaseBase object for profile plots like pseudo sections.
Provides functionality for creating profile views of MT data along a linear transect.
- Parameters:
tf_list (list or MTCollection) – List of transfer function objects or MTCollection
**kwargs (dict) – Additional keyword arguments for PlotBase parent class and profile settings
- mt_data
MT data to plot
- Type:
list or MTCollection
- profile_vector
Profile direction vector
- Type:
array-like | None
- profile_angle
Profile angle in degrees
- Type:
float | None
- profile_line
Profile line parameters (slope, intercept)
- Type:
tuple | None
- profile_reverse
Whether to reverse profile direction, by default False
- Type:
bool
- x_stretch
Horizontal stretching factor for profile, by default 5000
- Type:
float
- y_stretch
Vertical stretching factor for profile, by default 1000
- Type:
float
- y_scale
Y-axis scale type (‘period’ or ‘frequency’), by default ‘period’
- Type:
str
- property rotation_angle: float
Get rotation angle for data.
- Returns:
Rotation angle in degrees
- Return type:
float
- class mtpy.imaging.mtplot_tools.PlotSettings(**kwargs)[source]
-
Comprehensive plot settings for MT data visualization.
Combines arrow and ellipse settings with figure, marker, line, and colorbar properties for creating publication-quality MT plots.
- Parameters:
**kwargs (dict, optional) – Keyword arguments to set any class attributes. Valid keys correspond to the extensive list of attributes below.
- fig_num
Figure number, by default 1
- Type:
int
- fig_dpi
Figure DPI resolution, by default 150
- Type:
int
- fig_size
Figure size (width, height) in inches, by default None
- Type:
tuple | None
- show_plot
Whether to display plot, by default True
- Type:
bool
- font_size
Base font size for plot text, by default 7
- Type:
int
- font_weight
Font weight (‘normal’, ‘bold’, etc.), by default ‘bold’
- Type:
str
- marker_size
Size of plot markers, by default 2.5
- Type:
float
- marker_lw
Line width of marker edges, by default 0.75
- Type:
float
- marker_color
Default marker color, by default ‘b’
- Type:
str
- marker
Default marker style, by default ‘v’
- Type:
str
- lw
Default line width, by default 1
- Type:
float
- plot_title
Plot title text, by default None
- Type:
str | None
- xy_ls, yx_ls, det_ls, skew_ls, strike_ls
Line styles for different components, by default ‘:’
- Type:
str
- xy_marker, yx_marker, det_marker, skew_marker
Marker styles for different components
- Type:
str
- strike_inv_marker, strike_pt_marker, strike_tip_marker
Marker styles for strike indicators
- Type:
str
- xy_color, yx_color, det_color, skew_color
RGB colors for different components
- Type:
tuple
- strike_inv_color, strike_pt_color, strike_tip_color
RGB colors for strike indicators
- Type:
tuple
- x_limits, y_limits, res_limits, phase_limits
Axis limits for various plot types
- Type:
tuple | None
- tipper_limits, strike_limits, skew_limits, pt_limits
Additional axis limits
- Type:
tuple | None
- plot_z
Whether to plot impedance, by default True
- Type:
bool
- plot_tipper
Tipper plotting mode (‘n’, ‘y’, ‘yri’), by default ‘n’
- Type:
str
- plot_pt
Whether to plot phase tensor, by default False
- Type:
bool
- plot_strike
Whether to plot strike, by default False
- Type:
bool
- plot_skew
Whether to plot skew, by default False
- Type:
bool
- text_size
Text annotation size, by default 7
- Type:
int
- text_weight
Text annotation weight, by default ‘normal’
- Type:
str
- text_color
Text annotation color, by default ‘k’
- Type:
str
- text_ha
Text horizontal alignment, by default ‘center’
- Type:
str
- text_va
Text vertical alignment, by default ‘baseline’
- Type:
str
- text_angle
Text rotation angle, by default 0
- Type:
float
- text_x_pad, text_y_pad
Text padding in x/y directions, by default 0
- Type:
float
- text_rotation
Additional text rotation, by default 0
- Type:
float
- subplot_left, subplot_right, subplot_bottom, subplot_top
Subplot spacing parameters
- Type:
float
- subplot_wspace, subplot_hspace
Width/height spacing between subplots
- Type:
float | None
- cb_orientation
Colorbar orientation (‘vertical’ or ‘horizontal’), by default ‘vertical’
- Type:
str
- cb_position
Colorbar position [left, bottom, width, height], by default None
- Type:
tuple | None
- property arrow_imag_properties: dict[str, str | float | bool]
Get matplotlib arrow properties for imaginary tipper component.
- Returns:
Dictionary of arrow kwargs including line width, colors, head dimensions, and length settings
- Return type:
dict[str, str | float | bool]
- property arrow_real_properties: dict[str, str | float | bool]
Get matplotlib arrow properties for real tipper component.
- Returns:
Dictionary of arrow kwargs including line width, colors, head dimensions, and length settings
- Return type:
dict[str, str | float | bool]
- property det_error_bar_properties: dict[str, str | float]
Get matplotlib errorbar properties for determinant component.
- Returns:
Dictionary of errorbar kwargs including marker style, size, colors, line styles, and cap properties
- Return type:
dict[str, str | float]
- property font_dict: dict[str, int | str]
Get font properties dictionary for matplotlib.
Adjusts key names based on matplotlib version for compatibility.
- Returns:
Font properties with ‘size’/’fontsize’ and ‘weight’/’fontweight’ depending on matplotlib version
- Return type:
dict[str, int | str]
- make_pt_cb(ax: Axes) mcb.Colorbar[source]
Create phase tensor colorbar.
Generates colorbar for phase tensor plots with appropriate color mapping, normalization, and labeling based on ellipse settings.
- Parameters:
ax (Axes) – Matplotlib axes to attach colorbar to
- Returns:
Configured matplotlib colorbar object
- Return type:
mcb.Colorbar
- property period_label_dict: dict[int, str]
Get LaTeX-formatted period labels for log10 scale.
- Returns:
Dictionary mapping integer exponents to LaTeX strings in format $10^{exponent}$ for range -20 to 20
- Return type:
dict[int, str]
- set_period_limits(period: ndarray) tuple[float, float][source]
Calculate period axis limits as powers of 10.
- Parameters:
period (np.ndarray) – Array of period values
- Returns:
Minimum and maximum limits as powers of 10 (floor and ceil)
- Return type:
tuple[float, float]
- set_phase_limits(phase: ndarray, mode: str = 'od') tuple[float, float] | list[float][source]
Calculate appropriate phase axis limits.
- Parameters:
phase (np.ndarray) – Phase array with shape (n_periods, 2, 2) for full tensor or (n_periods,) for determinant
mode (str, optional) – Plotting mode: - ‘od’: off-diagonal components (0-90 range with adjustments) - ‘d’: diagonal components (-180 to 180) - ‘det’ or ‘det_only’: determinant phase by default ‘od’
- Returns:
[min_limit, max_limit] in degrees Defaults to [0, 90] for ‘od’ or [-180, 180] for others if calculation fails
- Return type:
tuple[float, float] | list[float]
- set_resistivity_limits(resistivity: ndarray, mode: str = 'od', scale: str = 'log') list[float][source]
Calculate appropriate resistivity axis limits.
- Parameters:
resistivity (np.ndarray) – Resistivity array with shape (n_periods, 2, 2) for full tensor or (n_periods,) for determinant
mode (str, optional) – Plotting mode: - ‘od’: off-diagonal components (xy, yx) - ‘d’: diagonal components (xx, yy) - ‘det’ or ‘det_only’: determinant only - ‘all’: all components by default ‘od’
scale (str, optional) – Scale type (‘log’ or ‘linear’), by default ‘log’
- Returns:
[min_limit, max_limit] as powers of 10 Defaults to [0.1, 10000] if calculation fails
- Return type:
list[float]
- property text_dict: dict[str, int | str | float]
Get text annotation properties dictionary.
- Returns:
Dictionary of text properties including size, weight, rotation angle, and color
- Return type:
dict[str, int | str | float]
- property xy_error_bar_properties: dict[str, str | float]
Get matplotlib errorbar properties for xy component.
- Returns:
Dictionary of errorbar kwargs including marker style, size, colors, line styles, and cap properties
- Return type:
dict[str, str | float]
- property yx_error_bar_properties: dict[str, str | float]
Get matplotlib errorbar properties for yx component.
- Returns:
Dictionary of errorbar kwargs including marker style, size, colors, line styles, and cap properties
- Return type:
dict[str, str | float]
- mtpy.imaging.mtplot_tools.add_raster(ax: Axes, raster_fn: str, add_colorbar: bool = True, **kwargs) tuple[Axes, mcb.Colorbar | None][source]
Add a raster image to axes using rasterio.
Overlays a georeferenced raster (e.g., GeoTIFF) on matplotlib axes with optional colorbar.
- Parameters:
ax (Axes) – Matplotlib axes to add raster to
raster_fn (str) – Path to raster file (must be readable by rasterio)
add_colorbar (bool, optional) – Whether to add colorbar, by default True
**kwargs (dict, optional) – Additional keyword arguments passed to rasterio.plot.show
- Returns:
Updated axes and colorbar (None if add_colorbar=False)
- Return type:
tuple[Axes, mcb.Colorbar | None]
- mtpy.imaging.mtplot_tools.get_log_tick_labels(ax: Axes, spacing: float = 1) tuple[list[str], list[float]][source]
Get LaTeX-formatted tick labels for logarithmic period axis.
Generates tick labels in format $10^{exponent}$ for valid tick positions.
- Parameters:
ax (Axes) – Axes to extract tick positions from
spacing (float, optional) – Spacing factor for tick positions, by default 1
- Returns:
Tick labels (LaTeX strings) and corresponding tick positions
- Return type:
tuple[list[str], list[float]]
- mtpy.imaging.mtplot_tools.griddata_interpolate(x: ndarray, y: ndarray, values: ndarray, new_x: ndarray, new_y: ndarray, interpolation_method: str = 'cubic') tuple[ndarray, ndarray, ndarray][source]
Interpolate scattered data to regular grid using scipy.interpolate.griddata.
- Parameters:
x (np.ndarray) – X coordinates of data points
y (np.ndarray) – Y coordinates of data points
values (np.ndarray) – Values at data points
new_x (np.ndarray) – Target x coordinates for interpolation
new_y (np.ndarray) – Target y coordinates for interpolation
interpolation_method (str, optional) – Interpolation method: ‘nearest’, ‘linear’, or ‘cubic’, by default ‘cubic’
- Returns:
grid_x : 2D array of x coordinates grid_y : 2D array of y coordinates image : 2D array of interpolated values
- Return type:
tuple[np.ndarray, np.ndarray, np.ndarray]
- mtpy.imaging.mtplot_tools.interpolate_to_map(plot_array: ndarray, component: str, cell_size: float = 0.002, n_padding_cells: int = 10, interpolation_method: str = 'delaunay', interpolation_power: float = 5, nearest_neighbors: int = 7) tuple[ndarray | Triangulation, ndarray, ndarray | None][source]
Interpolate MT data to regular map grid.
Dispatcher function that selects appropriate interpolation method. Supports both griddata-based (nearest, linear, cubic) and triangulation-based (delaunay, fancy) methods.
- Parameters:
plot_array (np.ndarray) – Structured array with ‘longitude’, ‘latitude’, and component fields
component (str) – Name of component to interpolate (e.g., ‘res_xy’, ‘phase_xy’)
cell_size (float, optional) – Size of grid cells in decimal degrees, by default 0.002
n_padding_cells (int, optional) – Number of padding cells around data extent, by default 10
interpolation_method (str, optional) – Interpolation method: - ‘nearest’, ‘linear’, ‘cubic’: scipy.interpolate.griddata methods - ‘delaunay’, ‘fancy’, ‘triangulate’: triangulation with IDW by default ‘delaunay’
interpolation_power (float, optional) – Power parameter for IDW in triangulation methods, by default 5
nearest_neighbors (int, optional) – Number of nearest neighbors for IDW, by default 7
- Returns:
grid_x or triangulation : Grid x coordinates (2D) or triangulation object grid_y or image : Grid y coordinates (2D) or interpolated values image or inside_indices : Interpolated values or boolean hull mask
- Return type:
tuple[np.ndarray | tri.Triangulation, np.ndarray, np.ndarray | None]
Notes
Return types differ by method: - griddata methods: (grid_x, grid_y, image) - triangulation methods: (triangulation, image, inside_indices)
- mtpy.imaging.mtplot_tools.plot_errorbar(ax: Axes, x_array: np.ndarray, y_array: np.ndarray, y_error: np.ndarray | None = None, x_error: np.ndarray | None = None, **kwargs) ErrorbarContainer[source]
Create error bar plot with customizable properties.
Convenience function to generate matplotlib errorbar plots with sensible defaults that can be overridden via kwargs.
- Parameters:
ax (Axes) – Matplotlib axes to plot on
x_array (np.ndarray) – Array of x values
y_array (np.ndarray) – Array of y values
y_error (np.ndarray | None, optional) – Array of y-direction error values, by default None
x_error (np.ndarray | None, optional) – Array of x-direction error values, by default None
**kwargs (dict, optional) – Additional errorbar properties: - color : marker, line, and error bar color - marker : marker style - mew : marker edge width - mec : marker edge color - ms : marker size - ls : line style - lw : line width - capsize : error bar cap size - capthick : error bar cap thickness - ecolor : error bar color - elinewidth : error bar line width - picker : pick radius in points
- Returns:
Matplotlib errorbar container with line data and error bars
- Return type:
ErrorbarContainer
- mtpy.imaging.mtplot_tools.plot_phase(ax: Axes, period: np.ndarray, phase: np.ndarray | None, error: np.ndarray | None, yx: bool = False, **properties) list[ErrorbarContainer | None][source]
Plot phase with error bars.
Plots only non-zero phase values. Optionally adds 180 degrees to yx component for proper quadrant representation.
- Parameters:
ax (Axes) – Matplotlib axes to plot on
period (np.ndarray) – Array of period values
phase (np.ndarray | None) – Array of phase values (degrees)
error (np.ndarray | None) – Array of phase error values
yx (bool, optional) – If True, adds 180 degrees to phase for yx component, by default False
**properties (dict, optional) – Additional errorbar properties passed to plot_errorbar
- Returns:
List containing errorbar container or [None] if no data
- Return type:
list[ErrorbarContainer | None]
- mtpy.imaging.mtplot_tools.plot_pt_lateral(ax: Axes, pt_obj, color_array: np.ndarray, ellipse_properties: dict, y_shift: float = 0, fig: Figure | None = None, edge_color: str | tuple | None = None, n_index: int = 0) tuple[Axes | None, mcb.Colorbar | None][source]
Plot phase tensor ellipses on lateral (period) axis.
Creates phase tensor ellipse plot with ellipses scaled by phimin/phimax and oriented by azimuth. Includes optional colorbar.
- Parameters:
ax (Axes) – Matplotlib axes to plot on
pt_obj (PhaseTensor) – Phase tensor object with frequency, phimin, phimax, and azimuth
color_array (np.ndarray) – Array of values for coloring ellipses
ellipse_properties (dict) – Dictionary with keys: - ‘size’: ellipse size scaling factor - ‘spacing’: spacing between ellipses on period axis - ‘colorby’: property to color by - ‘cmap’: colormap name - ‘range’: [min, max, step] for color mapping
y_shift (float, optional) – Vertical offset for ellipse centers, by default 0
fig (Figure | None, optional) – Figure for adding colorbar, by default None
edge_color (str | tuple | None, optional) – Color for ellipse edges, by default None
n_index (int, optional) – Index for controlling colorbar creation (only at 0), by default 0
- Returns:
Colorbar axes and colorbar object (both None if n_index != 0)
- Return type:
tuple[Axes | None, mcb.Colorbar | None]
- mtpy.imaging.mtplot_tools.plot_resistivity(ax: Axes, period: np.ndarray, resistivity: np.ndarray | None, error: np.ndarray | None, **properties) list[ErrorbarContainer | None][source]
Plot apparent resistivity with error bars.
Plots only non-zero resistivity values on the given axes.
- Parameters:
ax (Axes) – Matplotlib axes to plot on
period (np.ndarray) – Array of period values
resistivity (np.ndarray | None) – Array of apparent resistivity values (ohm-m)
error (np.ndarray | None) – Array of resistivity error values
**properties (dict, optional) – Additional errorbar properties passed to plot_errorbar
- Returns:
List containing errorbar container or [None] if no data
- Return type:
list[ErrorbarContainer | None]
- mtpy.imaging.mtplot_tools.plot_tipper_lateral(axt: Axes | None, t_obj, plot_tipper: str | bool, real_properties: dict, imag_properties: dict, font_size: int = 6, legend: bool = True, zero_reference: bool = False, arrow_direction: int = 1) tuple[Axes | None, list[Line2D] | None, list[str] | None][source]
Plot tipper arrows on lateral (period) axis.
Creates tipper arrow plot showing real and/or imaginary components as arrows with magnitude and direction.
- Parameters:
axt (Axes | None) – Matplotlib axes to plot on (returns None if None)
t_obj (Tipper) – Tipper object with frequency, mag_real, angle_real, mag_imag, and angle_imag attributes
plot_tipper (str | bool) – Tipper plotting mode: - ‘yri’: plot both real and imaginary - ‘yr’: plot real only - ‘yi’: plot imaginary only - ‘y’: plot both - False/None: no plot
real_properties (dict) – Arrow properties for real component (matplotlib arrow kwargs)
imag_properties (dict) – Arrow properties for imaginary component (matplotlib arrow kwargs)
font_size (int, optional) – Font size for axis labels and legend, by default 6
legend (bool, optional) – Whether to show legend, by default True
zero_reference (bool, optional) – Whether to plot zero reference line, by default False
arrow_direction (int, optional) – Arrow direction multiplier (1 or -1), by default 1
- Returns:
Updated axes, legend handles list, and legend labels list All None if axt is None or t_obj is None
- Return type:
tuple[Axes | None, list[Line2D] | None, list[str] | None]
- mtpy.imaging.mtplot_tools.triangulate_interpolation(x: ndarray, y: ndarray, values: ndarray, padded_x: ndarray, padded_y: ndarray, new_x: ndarray, new_y: ndarray, nearest_neighbors: int = 7, interp_pow: float = 4) tuple[Triangulation, ndarray, ndarray][source]
Interpolate using Delaunay triangulation and inverse distance weighting.
Creates triangulation on target grid and uses IDW interpolation with k-nearest neighbors from source data points. Masks triangles outside the convex hull.
- Parameters:
x (np.ndarray) – X coordinates of source data points
y (np.ndarray) – Y coordinates of source data points
values (np.ndarray) – Values at source data points
padded_x (np.ndarray) – Padded x coordinates defining convex hull boundary
padded_y (np.ndarray) – Padded y coordinates defining convex hull boundary
new_x (np.ndarray) – Target x coordinates for interpolation
new_y (np.ndarray) – Target y coordinates for interpolation
nearest_neighbors (int, optional) – Number of nearest neighbors for IDW interpolation, by default 7
interp_pow (float, optional) – Power parameter for IDW (higher = more weight to closer points), by default 4
- Returns:
triangulation : Matplotlib triangulation object with mask image : Flattened array of interpolated values inside_indices : Boolean array indicating triangles inside hull
- Return type:
tuple[tri.Triangulation, np.ndarray, np.ndarray]