Utils

utdquake.utils.plot

plot.py (This can be improved significantly with more modularization later… I am a bit lazy to do it now)

Functions for plotting seismic data, including:

  • Network and event overview maps (plot_overview, plot_utdq_overview)

  • Seismic statistics and histograms (plot_stats, plot_pick_histograms)

  • Uncertainty visualization (plot_uncertainty_boxplots)

  • Utility functions like add_scalebar

  • Multi-panel QC plot for multiple seismic phases.

Dependencies: - numpy, pandas, matplotlib, seaborn, scipy - cartopy (for geographic plotting) - .utils (custom helpers: compute_region, human_format, etc.)

Author: Emmanuel David Castillo Taborda Date: 2026-01-30

utdquake.utils.plot.add_scalebar(ax, region, location='upper left')[source]

Add a simple scale bar to a map.

Parameters:
  • ax (plt.Axes) – Axes to draw the scale bar on.

  • region (tuple) – Map extent as (lon_min, lon_max, lat_min, lat_max).

  • location (str, optional) – Location of the scale bar. Options: ‘upper left’, ‘upper right’, ‘lower left’, ‘lower right’. Default is ‘upper left’.

Return type:

None

Examples

>>> fig, ax = plt.subplots()
>>> region = (-70, -60, 2, 10)
>>> add_scalebar(ax, region, location='lower left')
utdquake.utils.plot.plot_network_station_density(df, savepath=None, show=False, dpi=300)[source]

Plot network station count vs geographic extent with event-based marker sizes. Color points by continent.

Parameters:
  • df (pandas.DataFrame) – Must contain the following columns: - ‘network’: network name - ‘approx_lon_min’, ‘approx_lon_max’, ‘approx_lat_min’, ‘approx_lat_max’ - ‘total_stations’: number of stations in the network - ‘events’: number of events in the network - ‘continent’: continent of the network

  • savepath (str, optional) – Path to save the figure. If None, figure is not saved.

  • show (bool, optional) – If True, displays the figure.

  • dpi (int, optional) – DPI for saving the figure. Default is 300.

Returns:

  • fig (matplotlib.figure.Figure) – The created figure object.

  • ax (matplotlib.axes.Axes) – The created axes object.

utdquake.utils.plot.plot_overview(events, stations, analysis=None, das=False, consider_calculated_stations=True, region=None, is_alaska=True, savepath=None, show=True)[source]

Plot a network overview with events, stations, and statistics.

Parameters:
  • events (pd.DataFrame) – Event table with columns: [‘longitude’, ‘latitude’, ‘time’, ‘magnitude’].

  • stations (pd.DataFrame) – Station table with columns: [‘longitude’, ‘latitude’, ‘calculated’, ‘confirmed’].

  • analysis (dict) – Dictionary with network statistics (events, stations, picks, etc.).

  • das (bool, optional) – If True, plot stations as a connected line (DAS-like). Defaults to False.

  • consider_calculated_stations (bool, optional) – If True, also plot calculated stations (if available). Defaults to True.

  • region (tuple, optional) – Map extent (lon_min, lon_max, lat_min, lat_max). Default: None.

  • is_alaska (bool, optional) – If True, use a projection suitable for Alaska. Default: True.

  • savepath (str, optional) – Path to save the figure. Default: None.

  • show (bool, optional) – If True, display the figure. Default: True.

Returns:

ax1: Global map with events and stations ax2: Regional map with events and stations ax3: Time vs Magnitude scatter + histogram ax4: Depth histogram ax5: Magnitude histogram

Return type:

fig , (ax1, ax2, ax3, ax4, ax5)

Examples

>>> plot_overview(df_events, df_stations, analysis_dict, region=(-70, -60, 2, 10))
>>> plot_overview(df_events, df_stations, analysis_dict, savepath="overview.png", show=False)
utdquake.utils.plot.plot_phase_count_radar_by_magnitude(events, show=True, savepath=None)[source]

Create radar plots of phase and station counts binned by magnitude.

For each magnitude range, the function displays the mean values of P phases, S phases, used phases, and station counts in a radar chart. Variability is represented using interquartile range (IQR) and the 10–90 percentile envelope.

Parameters:
  • events (pandas.DataFrame) – DataFrame containing at least the following columns: ‘magnitude’, ‘p_phase_count’, ‘s_phase_count’, ‘used_phase_count’, and ‘station_count’.

  • show (bool, optional) – Whether to display the figure on screen (default is True).

  • savepath (str or None, optional) – If provided, the figure will be saved to this path with dpi=300.

Return type:

None

utdquake.utils.plot.plot_pick_histograms(df, savepath=None, show=True)[source]

Plot histograms of P picks, S picks, and Vp/Vs ratio (Wadati method).

Parameters:
  • df (pd.DataFrame) – Must include columns: [‘phase’, ‘origin_id’, ‘origin_time’, ‘time’, ‘network’, ‘station’].

  • savepath (str, optional) – Path to save the figure. Default: None.

  • show (bool, optional) – If True, display the figure. Default: True.

Return type:

Tuple[Figure, list]

Returns:

  • fig (plt.Figure) – Figure object.

  • axes (list) – List of axes objects.

Examples

>>> plot_pick_histograms(df_picks)
>>> fig, axes = plot_pick_histograms(df_picks, savepath="pick_hist.png", show=False)
utdquake.utils.plot.plot_pick_stats(df, distance_type='epicentral', savepath=None, show=True)[source]

Plot summary statistics for seismic picks (P, S, and S-P) as jointplots.

The function computes: - First and last P travel times per event. - First and last S travel times per event. - First and last S-P times for stations with both P and S picks. - Corresponding distances (either epicentral or hypocentral).

It creates individual seaborn jointplots (scatter + marginal histograms), saves them temporarily as PNGs, and combines them into a single multi-panel matplotlib figure.

Parameters:
  • df (pandas.DataFrame) – DataFrame containing pick information. Expected columns: - “origin_id” - “origin_time” - “time” - “phase” - “distance” (in degrees) - “linear_hyp_distance” (in km, optional) - “network” - “station”

  • distance_type (str, default "epicentral") – Which distance to use: - “epicentral”: horizontal distance from epicenter (converted from degrees to km). - “hypocentral”: approximate distance from hypocenter (linear approx.) (requires ‘linear_hyp_distance’).

  • savepath (str or pathlib.Path, optional) – Path to save the final figure.

  • show (bool, default True) – Whether to display the figure.

Returns:

Combined multi-panel figure of all jointplots.

Return type:

matplotlib.figure.Figure

utdquake.utils.plot.plot_single_tt_qc(df, phase, model=None, zscore_threshold=2, show_outliers=True, show_text=True, show_models=None, show_global_model=True, distance_col='linear_hyp_distance', tt_col='travel_time', x_limits=None, y_limits=None, ax=None, scatter_args=None)[source]

Plot travel-time QC for a single seismic phase.

Highlights outliers based on z-score, optionally overlays model predictions and global trends.

Parameters:
  • df (pd.DataFrame) – Travel-time data containing distance, travel time, phase, and z-score.

  • phase (str) – Seismic phase to plot (e.g., “P”, “S”).

  • model (optional) – TravelTimeModel object containing model predictions.

  • zscore_threshold (float, optional) – Z-score threshold to mark outliers (default: 2).

  • show_outliers (bool, optional) – Whether to highlight outliers (default: True).

  • show_text (bool, optional) – Display fraction of valid points inside z-score threshold (default: True).

  • show_models (list of str, optional) – Columns in model to display (example: [“travel_time_p50”]). See in qc/pick_models

  • show_global_model (bool, optional) – Show global trend bounds (default: True).

  • distance_col (str, optional) – Column name for distance (default: “linear_hyp_distance”).

  • tt_col (str, optional) – Column name for travel time (default: “travel_time”).

  • x_limits (tuple, optional) – X-axis limits (default: auto from data).

  • y_limits (tuple, optional) – Y-axis limits (default: auto from data).

  • ax (plt.Axes, optional) – Axes to plot on (default: creates new figure).

  • scatter_args (dict, optional) – Additional arguments for scatter plot (default: None).

Returns:

Axes object containing the plot.

Return type:

plt.Axes

utdquake.utils.plot.plot_station_location_uncertainty(df, savepath, dpi=300, show=True)[source]

Plot and compare confirmed vs calculated station locations.

This function visualizes the difference between confirmed and calculated station coordinates. It plots a scatter plot of confirmed coordinates and overlays calculated coordinates, allowing for quick inspection of station location accuracy.

Parameters:
  • df (pd.DataFrame) – Must contain the following columns: - ‘confirmed_latitude’ - ‘confirmed_longitude’ - ‘calculated_latitude’ - ‘calculated_longitude’

  • savepath (str) – Path to save the resulting plot (e.g., ‘station_uncertainty.png’).

  • dpi (int, optional) – Resolution of the saved figure. Default is 300.

  • show (bool, optional) – If True, display the figure interactively. Default is True.

Return type:

None

Examples

>>> plot_station_location_uncertainty(df_stations, "uncertainty.png", show=True)
utdquake.utils.plot.plot_station_map(ax, df, region)[source]

Plot calculated and confirmed station locations on a geographic map.

This function uses Cartopy to display station locations, distinguishing between stations that are only calculated and those that are both calculated and confirmed. It also adds a scale bar and a legend.

Parameters:
  • ax (matplotlib.axes.Axes) – The matplotlib axes object where the map will be drawn.

  • df (pandas.DataFrame) – DataFrame containing station information with at least the following columns: - ‘network’ : str, network code - ‘station’ : str, station code - ‘confirmed’ : int, 1 if station is confirmed, 0 otherwise - ‘calculated’ : int, 1 if station is calculated, 0 otherwise - ‘confirmed_latitude’, ‘confirmed_longitude’ : float, coordinates of confirmed stations - ‘calculated_latitude’, ‘calculated_longitude’ : float, coordinates of calculated stations

  • region (list) – Geographic extent of the map in the format [min_lon, max_lon, min_lat, max_lat].

Returns:

The axes object with the plotted station locations.

Return type:

matplotlib.axes.Axes

Raises:

ImportError – If Cartopy is not installed.

Examples

>>> import matplotlib.pyplot as plt
>>> fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
>>> ax = plot_station_map(ax, df_stations, [-120, -70, 20, 50])
>>> plt.show()
utdquake.utils.plot.plot_stats(events, picks=None, savepath=None, show=True)[source]

Plot a 5-panel figure with earthquake statistics.

Panels include: depth, magnitude, epicentral distance, azimuthal gap, azimuth distribution.

Parameters:
  • events (pd.DataFrame) – Events table with columns: [‘time’, ‘depth’, ‘magnitude’, ‘azimuthal_gap’].

  • picks (pd.DataFrame, optional) – Picks table for distance and azimuth calculations. Default: None.

  • savepath (str, optional) – Path to save the figure. Default: None.

  • show (bool, optional) – If True, display the figure. Default: True.

Return type:

Tuple[Figure, Dict[str, Axes]]

Returns:

  • fig (plt.Figure) – Figure object.

  • axes_dict (dict) – Dictionary with axes for each subplot: {‘depth’, ‘magnitude’, ‘epicentral_distance’, ‘azimuthal_gap’, ‘azimuth’}.

Examples

>>> fig, axes = plot_stats(df_events)
>>> fig, axes = plot_stats(df_events, df_picks, savepath="stats.png", show=False)
utdquake.utils.plot.plot_stats_from_stats(stats, savepath=None, show=True)[source]

Plot a 5-panel figure using precomputed network stats.

Panels: depth, magnitude, epicentral distance, azimuthal gap, azimuth distribution.

Parameters:
  • stats (dict) –

    These keys are typically generated by Network.compute_stats(). Precomputed statistics dictionary. Expected keys:

    • ’depth_values’np.ndarray

      Depths of events in kilometers.

    • ’magnitude_values’np.ndarray

      Magnitudes of events.

    • ’distance_bins’np.ndarray

      Bin edges for epicentral distances [km].

    • ’epi_dist_counts_P’np.ndarray

      Counts of P-phase picks in each distance bin.

    • ’epi_dist_counts_S’np.ndarray

      Counts of S-phase picks in each distance bin.

    • ’az_gap_counts’np.ndarray

      Counts per azimuthal gap bin (typically 12 bins around 360°).

    • ’az_gap_bins’np.ndarray

      Bin edges for azimuthal gap (radians).

    • ’azimuth_counts’np.ndarray, optional

      Counts per azimuth bin for station distribution or picks.

    • ’azimuth_bins’np.ndarray, optional

      Bin edges for azimuth (radians).

  • savepath (str, optional) – Path to save the figure. Default: None.

  • show (bool, optional) – If True, display the figure. Default: True.

Return type:

Tuple[Figure, Dict[str, Axes]]

Returns:

  • fig (plt.Figure) – The Matplotlib figure object containing the 5 panels.

  • axes_dict (dict) – Dictionary of axes for each subplot: {

    ’depth’: ax1, ‘magnitude’: ax2, ‘epicentral_distance’: ax3, ‘azimuthal_gap’: ax4, ‘azimuth’: ax5

    }

Notes

  • Depth and magnitude panels use log-scaled y-axis.

  • Epicentral distance panel shows P and S phase counts mirrored around zero.

  • Polar plots show the distribution of azimuthal gaps and azimuths with color-coded percentages.

  • The function does not save or show the figure; use plt.show() or fig.savefig() externally.

Example

>>> fig, axes = plot_stats_from_stats(stats)
>>> plt.show()
utdquake.utils.plot.plot_travel_time_qc(df, add_inset=True, zscore_threshold=2, show_outliers=True, show_text=True, models=None, show_models=None, show_global_model=False, show_legend=True, distance_col='linear_hyp_distance', tt_col='travel_time', x_limits=None, y_limits=None, x_axins_limits=(0, 30), y_axins_limits=(0, 10), axes=None, axins=None, turn_off_empty_axes=True, scatter_args=None, savepath=None)[source]

Plot multi-phase travel-time QC with optional inset zooms.

Parameters:
  • df (pd.DataFrame) – Travel-time data with multiple phases.

  • add_inset (bool, optional) – Add zoomed inset plots (default: True).

  • zscore_threshold (float, optional) – Z-score threshold for outlier detection (default: 2).

  • show_outliers (bool, optional) – Whether to highlight outliers (default: True).

  • show_text (bool, optional) – Show text annotations on each subplot (default: True).

  • models (dict, optional) – Dictionary of TravelTimeModel objects keyed by phase.

  • show_models (list of str, optional) – Columns in model to plot (default: [“travel_time_p50”]).

  • show_global_model (bool, optional) – Display global trend bounds (default: False).

  • show_legend (bool, optional) – Whether to show a unified legend (default: True).

  • distance_col (str, optional) – Column name for distance (default: “linear_hyp_distance”).

  • tt_col (str, optional) – Column name for travel time (default: “travel_time”).

  • x_limits (tuple,dict, optional) – X-axis limits for main plots (default: auto from data). If it is a dict, it should be keyed by phase name (e.g., {“P”: (0, 100), “S”: (0, 200)}).

  • y_limits (tuple,dict optional) – Y-axis limits for main plots (default: auto from data). If it is a dict, it should be keyed by phase name (e.g., {“P”: (0, 100), “S”: (0, 200)}).

  • x_axins_limits (tuple, optional) – X-axis limits for inset (default: (0, 30)). If it is a dict, it should be keyed by phase name (e.g., {“P”: (0, 100), “S”: (0, 200)}).

  • y_axins_limits (tuple, optional) – Y-axis limits for inset (default: (0, 10)). If it is a dict, it should be keyed by phase name (e.g., {“P”: (0, 100), “S”: (0, 200)}).

  • axes (np.ndarray, optional) – Pre-existing axes array to plot on (default: None, creates new). The order of phases is always P, Pn, Pg, S, Sn, Sg. Therefore, if providing axes, ensure they are in this order and have at least 6 axes.

  • scatter_args (dict, optional) – Additional arguments for scatter plots (default: None).

  • savepath (str, optional) – Path to save figure (default: None).

Return type:

Tuple[Figure, ndarray, List[Axes]]

Returns:

  • fig (plt.Figure) – The created figure.

  • axes (np.ndarray) – Array of axes for each phase subplot.

  • all_axins (list of plt.Axes) – List of inset axes.

  • legend_info (tuple) – (legend_handles, legend_labels) for the unified legend.

utdquake.utils.plot.plot_travel_time_vs_distance(picks, distance_unit='degrees', log_scale=False, show=True, savepath=None, point_size=5, chunk_size=50000)[source]

Plot travel time versus distance for seismic picks.

Works with: - pandas DataFrame - streaming iterable datasets

Parameters:
  • picks (pandas.DataFrame or iterable) – Either a DataFrame with picks or a streaming iterator.

  • distance_unit (str, optional) – “degrees” (default) or “km”

  • log_scale (bool, optional) – Whether to use logarithmic scale on the x-axis.

  • show (bool, optional) – Whether to display the plot.

  • savepath (str or None, optional) – Path to save the figure.

  • point_size (int, optional) – Size of scatter points.

  • chunk_size (int, optional) – Number of records to accumulate before plotting when using streaming input.

utdquake.utils.plot.plot_travel_time_vs_distance_zscore(picks, phase=None, distance_unit='degrees', log_scale=False, show=True, savepath=None, point_size=5, zmax=3.0, x_lim=None, y_lim=None, add_inset=True, x_axins_limits=(0, 30), y_axins_limits=(0, 10))[source]

Plot travel time versus distance colored by z-score values.

This function visualizes seismic travel times and highlights anomalous picks using z-score statistics. Picks classified as inliers are colored according to their absolute z-score values, while outliers are displayed in gray.

Optionally, a zoomed inset can be added to highlight near-source arrivals.

Parameters:
  • picks (pandas.DataFrame) –

    Input DataFrame containing seismic pick information.

    Required columns depend on the selected distance_unit:

    Common required columns:

    • travel_time

    • phase

    • travel_time_zscore

    Additional distance column:

    • distance for "degrees" or "km"

    • linear_hyp_distance for "hypo_km"

  • phase (str or None, default=None) – Seismic phase to plot. If None, all phases are included.

  • distance_unit (str, default="degrees") –

    Distance representation used for the x-axis.

    Supported options are:

    • "degrees"

    • "km"

    • "hypo_km"

  • log_scale (bool, default=False) – If True, apply logarithmic scaling to the x-axis.

  • show (bool, default=True) – If True, display the figure.

  • savepath (str or None, default=None) – Output path used to save the generated figure.

  • point_size (int, default=5) – Marker size used in scatter plots.

  • zmax (float, default=3.0) –

    Maximum z-score value used for color normalization.

    Picks with absolute z-score values larger than zmax are classified as outliers.

  • x_lim (tuple or None, default=None) – X-axis limits in the form (xmin, xmax).

  • y_lim (tuple or None, default=None) – Y-axis limits in the form (ymin, ymax).

  • add_inset (bool, default=True) – If True, add a zoomed inset axis.

  • x_axins_limits (tuple, default=(0, 30)) – X-axis limits for the inset axes.

  • y_axins_limits (tuple, default=(0, 10)) – Y-axis limits for the inset axes.

Raises:
  • ValueError – If picks is not a pandas DataFrame.

  • ValueError – If required columns are missing.

  • ValueError – If no picks are available for the selected phase.

Notes

  • Absolute z-score values are used for thresholding.

  • Outliers are plotted in gray.

  • A colorbar indicates z-score magnitude.

  • Approximate conversion factor: 1 degree = 111.19 km.

Examples

Plot all phases:

>>> plot_travel_time_vs_distance_zscore(df)

Plot only P-phase arrivals:

>>> plot_travel_time_vs_distance_zscore(
...     df,
...     phase="P",
... )

Plot using hypocentral distance in kilometers:

>>> plot_travel_time_vs_distance_zscore(
...     df,
...     distance_unit="hypo_km",
... )
utdquake.utils.plot.plot_uncertainty_boxplots(df, figsize=(4, 6), dpi=300, savepath=None, show=True)[source]

Plot boxplots for horizontal, vertical uncertainties and standard error.

Parameters:
  • df (pd.DataFrame) – Must include columns: [‘horizontal_uncertainty’, ‘vertical_uncertainty’, ‘standard_error’].

  • figsize (tuple, optional) – Figure size. Default: (4, 6).

  • dpi (int, optional) – Figure resolution. Default: 300.

  • savepath (str, optional) – Path to save figure. Default: None.

  • show (bool, optional) – If True, display the figure. Default: True.

Return type:

Tuple[Figure, list]

Returns:

  • fig (plt.Figure) – Figure object.

  • axes (list) – List of axes objects.

Examples

>>> plot_uncertainty_boxplots(df)
>>> plot_uncertainty_boxplots(df, savepath="uncertainty.png", show=False)
utdquake.utils.plot.plot_utdq_overview(events, stations, analysis, das=False, consider_calculated_stations=True, region=None, savepath=None, show=False)[source]

Plot a two-panel map overview: - Top: Earthquake epicenters - Bottom: Seismic stations

Parameters:
  • events (pandas.DataFrame) – Must contain ‘longitude’ and ‘latitude’.

  • stations (pandas.DataFrame) – Must contain ‘longitude’ and ‘latitude’.

  • analysis (dict) – Summary statistics (events, arrivals, stations).

  • das (bool, optional) – If True, plot stations as a connected line (DAS-like). Defaults to False.

  • consider_calculated_stations (bool, optional) – If True, also plot calculated stations (if available). Defaults to True.

  • region (tuple or None, optional) – Map extent as (lon_min, lon_max, lat_min, lat_max). Defaults to global view.

  • savepath (str, optional) – Output savepath.

  • show (bool, optional) – If True, displays the figure.

Return type:

None

utdquake.utils.plot.plot_venn(ax, df)[source]

Draw a Venn diagram comparing calculated and confirmed stations.

This function visualizes the overlap between calculated and confirmed stations using a two-set Venn diagram. It highlights stations that are only calculated, only confirmed, and those present in both.

Parameters:
  • ax (matplotlib.axes.Axes) – Axes object to draw the Venn diagram on.

  • df (pandas.DataFrame) – DataFrame containing boolean or binary columns: - ‘calculated’: 1 if station is calculated, 0 otherwise - ‘confirmed’: 1 if station is confirmed, 0 otherwise

Returns:

The axes object with the Venn diagram drawn.

Return type:

matplotlib.axes.Axes

Raises:

ImportError – If the matplotlib-venn library is not installed.

Examples

>>> fig, ax = plt.subplots()
>>> plot_venn(ax, df_stations)
>>> plt.show()
utdquake.utils.plot.setup_map(ax, region)[source]

Configure a Cartopy map axis with standard geographic features.

This function sets up a map with coastlines, borders, states, land, ocean, lakes, rivers, and gridlines. It also applies a geographic extent defined by the region.

Parameters:
  • ax (matplotlib.axes.Axes) – The matplotlib axes object where the map will be drawn. Typically created using plt.subplots(subplot_kw={‘projection’: ccrs.PlateCarree()}).

  • region (list) – Geographic extent of the map in the format [min_lon, max_lon, min_lat, max_lat].

Returns:

  • axmatplotlib.axes.Axes

    The configured axes with map features.

  • glcartopy.mpl.gridliner.Gridliner

    Gridliner object for further customization.

Return type:

tuple

Raises:

ImportError – If the Cartopy library is not installed.

Examples

>>> import matplotlib.pyplot as plt
>>> import cartopy.crs as ccrs
>>> fig, ax = plt.subplots(subplot_kw={'projection': ccrs.PlateCarree()})
>>> ax, gl = setup_map(ax, [-120, -70, 20, 50])
>>> plt.show()
utdquake.utils.plot.tune_zoomed_travel_time_qc(axins, xlim=(0, 15), ylim=(0, 50))[source]

Configure a zoomed inset plot for travel-time QC.

Ensures proper limits, custom tick labels, minor adjustments, and removes axis labels for the inset.

Parameters:
  • axins (plt.Axes) – Axes object for the inset plot.

  • xlim (tuple, optional) – X-axis limits for the inset (default: (0, 15)).

  • ylim (tuple, optional) – Y-axis limits for the inset (default: (0, 50)).

Returns:

The configured inset axes.

Return type:

plt.Axes

utdquake.utils.utils

Utility functions for UTDQuake package.

This module provides helper functions for: - Computing plot regions for events and stations - Formatting large numbers - Formatting dates for plots - Creating custom colormaps - Summarizing networks (stations and events)

Modules required: - numpy - pandas - matplotlib

utdquake.utils.utils.compute_region(df_events, df_stations, padding=0.2, global_region=None, how='events', rm_outliers=False)[source]

Compute a bounding box for plotting events and stations. Handles dateline wrap-around.

Parameters:
  • df_events (pd.DataFrame) – Events table with ‘longitude’ and ‘latitude’ columns.

  • df_stations (pd.DataFrame) – Stations table with ‘longitude’ and ‘latitude’ columns.

  • padding (float, optional) – Fraction of span to add as padding (default is 0.2).

  • global_region (tuple, optional) – If provided, returns this region directly (lon_min, lon_max, lat_min, lat_max).

  • how (str, optional) – Which data to use: ‘events’, ‘stations’, or ‘both’ (default ‘events’).

  • rm_outliers (bool, optional) – If True, remove extreme outliers beyond 6 std deviations.

Returns:

(lon_min, lon_max, lat_min, lat_max)

Return type:

tuple

Raises:

ValueError – If no valid coordinates exist or invalid how argument.

Examples

>>> compute_region(df_events, df_stations, padding=0.1, how="both")
(-118.5, -115.2, 33.8, 36.1)
utdquake.utils.utils.create_green_to_orange_cmap(name='green_to_orange', n_colors=256)[source]

Create a colormap that transitions from green to orange (#ec7524).

Parameters:
  • name (str, optional) – Name of the colormap (default ‘green_to_orange’).

  • n_colors (int, optional) – Number of discrete colors in the colormap (default 256).

Returns:

Custom green-to-orange colormap.

Return type:

matplotlib.colors.LinearSegmentedColormap

Examples

>>> cmap = create_green_to_orange_cmap()
>>> type(cmap)
<class 'matplotlib.colors.LinearSegmentedColormap'>
utdquake.utils.utils.get_network_summary(stations, events, das=False)[source]

Compute summary statistics for a seismic network.

Parameters:
  • stations (pd.DataFrame) – Stations table. Must contain columns: [‘network’, ‘station’, ‘confirmed’, ‘calculated’].

  • events (pd.DataFrame) – Events table. Must contain columns: [‘latitude’, ‘longitude’, ‘time’, ‘p_phase_count’, ‘s_phase_count’].

  • das (bool, optional) – Whether to use DAS dataset. Default is False.

Returns:

Dictionary with summary statistics: - events : int

Number of events

  • p_arrivalsint

    Total P-phase picks

  • s_arrivalsint

    Total S-phase picks

  • total_stationsint

    Number of stations

  • located_stationsint

    Number of stations that have their location either confirmed or calculated

  • confirmed_stationsint

    Number of confirmed stations

  • calculated_stationsint

    Number of calculated stations

  • only_calculated_stationsint

    Number of stations that are calculated but not confirmed

  • start_timestr

    Earliest event time

  • end_timestr

    Latest event time

Return type:

dict

Examples

>>> get_network_summary(df_stations, df_events)
{'events': 10, 'p_arrivals': 30, ...}
utdquake.utils.utils.human_format(num)[source]

Format large numbers with K/M suffix for plotting.

Parameters:

num (float) – Number to format.

Returns:

Formatted string.

Return type:

str

Examples

>>> human_format(999)
'999'
>>> human_format(1200)
'1.2K'
>>> human_format(1500000)
'1.5M'
utdquake.utils.utils.smart_date_formatter(bins)[source]

Create a smart date formatter for matplotlib axes based on date range.

Parameters:

bins (array-like) – Sequence of datetime-like objects.

Returns:

Formatter to be used with matplotlib axes.

Return type:

matplotlib.ticker.FuncFormatter

Examples

>>> import pandas as pd
>>> bins = pd.date_range("2026-01-01", periods=10)
>>> fmt = smart_date_formatter(bins)
>>> fmt(pd.Timestamp("2026-01-01").toordinal())
'2026\nJan'