pycsamt.api.plot#

pycsamt.api.plot#

Global plot-export configuration for pyCSAMT.

Every pyCSAMT plot function returns a Figure or Axes. Saving that object through save_fig() (or PlotConfig.save()) automatically honours whatever format, DPI, and output directory you have configured once — instead of having to repeat the same savefig kwargs in every script.

Quick start#

Single format (default is PNG):

from pycsamt.api.plot import save_fig, set_fmt, set_dpi

ax = plot_phase_tensor_psection(sites)
save_fig(ax, "output/fig_pt")          # → fig_pt.png

Switch the global format:

set_fmt("svg")
save_fig(ax, "output/fig_pt")          # → fig_pt.svg

Additive — keep the default PNG plus add SVG:

set_fmt("+svg")
save_fig(ax, "output/fig_pt")          # → fig_pt.png  +  fig_pt.svg

Multiple explicit formats (no PNG unless listed):

set_fmt("svg", "pdf")
save_fig(ax, "output/fig_pt")          # → fig_pt.svg  +  fig_pt.pdf

Additive stack — PNG + SVG + PDF:

set_fmt("+svg", "+pdf")
# equivalent:
PLOT_CONFIG.fmt = ["+svg", "+pdf"]

Per-call override (does not change the global config):

save_fig(ax, "output/fig_pt", fmt="eps")

Context manager (reverts on exit):

from pycsamt.api.plot import PLOT_CONFIG
with PLOT_CONFIG.context(fmt=["+svg"], dpi=300):
    save_fig(fig, "publication/fig_pt")   # → .png + .svg @ 300 DPI
# back to previous config

Set a global output directory:

set_savedir("~/figures")
save_fig(ax, "fig_pt")     # → ~/figures/fig_pt.png

Global DPI:

set_dpi(300)

External control#

Any attribute can be set without modifying Python code via:

  1. Environment variables (highest precedence):

    PYCSAMT_FMT="+svg,+pdf"  PYCSAMT_DPI=300  python make_figures.py
    

    PYCSAMT_FMT is a comma-separated list of format tokens (+ prefix supported). Other variables: PYCSAMT_DPI, PYCSAMT_SAVEDIR, PYCSAMT_TRANSPARENT, PYCSAMT_BBOX.

  2. Config file (pycsamt_plot.cfg in the working directory, or ~/.pycsamt/plot.cfg as a user-global fallback):

    [plot]
    fmt        = +svg, +pdf
    dpi        = 300
    savedir    = ~/my_figures
    transparent = false
    bbox_inches = tight
    

    Local file takes precedence over the home-dir file. Both are read at import time and overridden by environment variables.

  3. Python API (programmatic, in scripts or notebooks):

    from pycsamt.api.plot import PLOT_CONFIG, set_fmt, set_dpi
    PLOT_CONFIG.dpi = 300
    set_fmt("+svg")
    

Format token rules#

Each token is a format extension (without the leading dot):

  • "png" → save as PNG only

  • "svg" → save as SVG only

  • "+svg" → save as base (default "png") and SVG

  • "+pdf" → save as base and PDF

  • A comma-separated string is split: "png,svg"["png", "svg"]

  • The base format can be changed via PLOT_CONFIG.base_fmt = "tiff"

Supported formats: png, svg, pdf, eps, tiff, jpg/jpeg.

PlotConfig attributes#

Module Attributes

PLOT_CONFIG

Package-level singleton.

Functions

add_colorbar(mappable, ax, *[, label, side, ...])

Attach an axes-aligned colorbar with smart tick density.

add_polar_colorbar(mappable, ax, *[, label, ...])

Attach a compact colorbar beside a polar axes.

load_plot_config([path])

(Re-)load a config file into PLOT_CONFIG.

reset_plot_config()

Reset PLOT_CONFIG to package defaults.

save_fig(fig_or_ax, path, *[, fmt, dpi])

Save a pyCSAMT figure using the global PLOT_CONFIG settings.

set_dpi(dpi)

Set the global raster DPI on PLOT_CONFIG.

set_fmt(*formats)

Set the global export format(s) on PLOT_CONFIG.

set_savedir(path)

Set the global output directory on PLOT_CONFIG.

write_default_config([path])

Write a template config file with the current PLOT_CONFIG values.

Classes

PlotConfig(*[, fmt, base_fmt, dpi, ...])

Global plot-export configuration singleton for pyCSAMT.

class pycsamt.api.plot.PlotConfig(*, fmt='png', base_fmt='png', dpi=150, bbox_inches='tight', transparent=False, facecolor='white', savedir=None, close_after_save=False, verbose=True)[source]#

Bases: object

Global plot-export configuration singleton for pyCSAMT.

The module-level PLOT_CONFIG instance is the recommended entry point. Mutate it once (at the top of your script or notebook) and every subsequent save_fig() call inherits those settings.

Parameters:
  • fmt (str or list[str], default "png") – Export format token(s). See format-token-rules above.

  • base_fmt (str, default "png") – The reference format for additive + tokens.

  • dpi (int, default 150) – Raster resolution. Use 300600 for publication.

  • bbox_inches (str, default "tight") – Passed to savefig().

  • transparent (bool, default False) – Transparent background.

  • facecolor (str, default "white") – Figure background colour.

  • savedir (str or Path or None) – If set, relative path arguments passed to save_fig() are resolved under this directory.

  • close_after_save (bool, default False) – Call plt.close(fig) after saving.

  • verbose (bool, default True) – Print a line for each file written.

Examples

Configure once:

from pycsamt.api.plot import PLOT_CONFIG, save_fig
PLOT_CONFIG.fmt = ["+svg"]
PLOT_CONFIG.dpi = 300
PLOT_CONFIG.savedir = "~/paper/figures"

Use the configure() helper (dotted-style not needed — direct attribute access is cleaner for this class):

PLOT_CONFIG.configure(fmt="+svg", dpi=300)
resolve_formats(fmt=None)[source]#

Return the resolved list of format strings for this call.

Parameters:

fmt (str, list[str], or None) – Per-call override. None → use fmt.

Returns:

Clean format strings (no +, no leading dot).

Return type:

list[str]

Examples

>>> cfg = PlotConfig(fmt="+svg")
>>> cfg.resolve_formats()
['png', 'svg']
>>> cfg.resolve_formats(fmt="pdf")
['pdf']
>>> cfg.resolve_formats(fmt=["+svg", "+pdf"])
['png', 'svg', 'pdf']
save(fig_or_ax, path, *, fmt=None, dpi=None, bbox_inches=None, transparent=None, facecolor=None, **savefig_kw)[source]#

Save fig_or_ax to one or more format files.

Parameters:
  • fig_or_ax (Figure or Axes) – Accepts either object type — the parent figure is extracted automatically from an Axes.

  • path (str or Path) – Base output path. The file extension is replaced (or added) per format. If relative and savedir is set, the path is resolved under savedir.

  • fmt (str, list[str], or None) – Per-call format override. Nonefmt.

  • dpi (int or None) – Per-call DPI override. Nonedpi.

  • bbox_inches (str or None) – Per-call override.

  • transparent (bool or None) – Per-call override.

  • facecolor (str or None) – Per-call override.

  • **savefig_kw – Additional keyword arguments forwarded to savefig().

Returns:

Paths of every file written (one per resolved format).

Return type:

list[Path]

Examples

>>> paths = PLOT_CONFIG.save(ax, "fig_pt")
>>> paths = PLOT_CONFIG.save(fig, "fig_pt", fmt="+svg", dpi=300)
configure(**kw)[source]#

Set multiple attributes at once.

Parameters:

**kw (Any) – Any writable PlotConfig attribute by name.

Return type:

None

Examples

>>> PLOT_CONFIG.configure(fmt="+svg", dpi=300, savedir="~/figures")
reset()[source]#

Reset to package defaults (ignores config file and env vars).

Return type:

None

context(**kw)[source]#

Temporarily override config attributes, then restore.

Parameters:

**kw (Any) – Any writable PlotConfig attribute by name.

Yields:

PlotConfig – The (temporarily modified) config object.

Return type:

Generator[PlotConfig, None, None]

Examples

>>> with PLOT_CONFIG.context(fmt="pdf", dpi=600):
...     save_fig(fig, "publication/fig")
>>> # config reverts here
to_dict()[source]#

Return current config as a plain dict.

Return type:

dict

summary()[source]#

Return a human-readable summary of the current config.

Return type:

str

pycsamt.api.plot.PLOT_CONFIG: PlotConfig = PlotConfig   fmt              = 'png'   resolved formats = ['png']   base_fmt         = 'png'   dpi              = 150   bbox_inches      = 'tight'   transparent      = False   facecolor        = 'white'   savedir          = None   close_after_save = False   verbose          = True#

Package-level singleton. Import and mutate to configure all save_fig() calls globally.

pycsamt.api.plot.add_colorbar(mappable, ax, *, label=None, side='right', size='3.5%', pad=0.06, max_ticks=6, tick_format=None, **colorbar_kw)[source]#

Attach an axes-aligned colorbar with smart tick density.

The helper creates a dedicated colorbar axes whose height matches the plotted axes. This avoids overly tall colorbars on equal-aspect maps and gives package plots a consistent colorbar geometry.

Parameters:
Return type:

Any

pycsamt.api.plot.add_polar_colorbar(mappable, ax, *, label=None, pad=0.1, shrink=0.72, aspect=20, max_ticks=5, tick_format=None, **colorbar_kw)[source]#

Attach a compact colorbar beside a polar axes.

Polar plots do not work well with the axes-divider geometry used by add_colorbar(), especially when figures are saved with tight bounding boxes. This helper keeps the same tick-density policy while using Matplotlib’s polar-friendly colorbar placement.

Parameters:
Return type:

Any

pycsamt.api.plot.save_fig(fig_or_ax, path, *, fmt=None, dpi=None, **kw)[source]#

Save a pyCSAMT figure using the global PLOT_CONFIG settings.

Parameters:
  • fig_or_ax (Figure or Axes) – The object to save.

  • path (str or Path) – Base output path (extension auto-managed per format).

  • fmt (str, list[str], or None) – Per-call format override. NonePLOT_CONFIG.fmt.

  • dpi (int or None) – Per-call DPI override. NonePLOT_CONFIG.dpi.

  • **kw – Forwarded to PlotConfig.save().

Returns:

File paths written.

Return type:

list[Path]

Examples

Default (PNG):

save_fig(ax, "output/fig_pt")

Override format for this call:

save_fig(ax, "output/fig_pt", fmt="svg")

Two formats for this call:

save_fig(ax, "output/fig_pt", fmt=["+svg"])
pycsamt.api.plot.set_fmt(*formats)[source]#

Set the global export format(s) on PLOT_CONFIG.

Parameters:

*formats (str) – One or more format tokens. A single "png" or "svg" sets that format exclusively. A "+svg" token adds SVG to the base format.

Return type:

None

Examples

>>> set_fmt("svg")          # only SVG
>>> set_fmt("+svg")         # PNG + SVG
>>> set_fmt("+svg", "+pdf") # PNG + SVG + PDF
>>> set_fmt("svg", "pdf")   # SVG + PDF (no PNG)
pycsamt.api.plot.set_dpi(dpi)[source]#

Set the global raster DPI on PLOT_CONFIG.

Parameters:

dpi (int) – Dots per inch. Typical values: 150 (screen), 300 (print), 600 (high-res print).

Return type:

None

Examples

>>> set_dpi(300)
pycsamt.api.plot.set_savedir(path)[source]#

Set the global output directory on PLOT_CONFIG.

Parameters:

path (str or Path) – Directory where save_fig() writes files when a relative path is given. Tilde (~) is expanded.

Return type:

None

Examples

>>> set_savedir("~/paper/figures")
>>> save_fig(ax, "fig_pt")   # → ~/paper/figures/fig_pt.png
pycsamt.api.plot.reset_plot_config()[source]#

Reset PLOT_CONFIG to package defaults.

Does not re-read config files or environment variables.

Examples

>>> reset_plot_config()
Return type:

None

pycsamt.api.plot.load_plot_config(path=None)[source]#

(Re-)load a config file into PLOT_CONFIG.

Parameters:

path (str, Path, or None) – Path to an INI config file with a [plot] section. None searches the default locations (pycsamt_plot.cfg in CWD then ~/.pycsamt/plot.cfg).

Raises:

FileNotFoundError – If path is given explicitly and does not exist.

Return type:

None

Examples

Load a specific file:

load_plot_config("project/plot_settings.cfg")

Reload defaults:

load_plot_config()
pycsamt.api.plot.write_default_config(path='pycsamt_plot.cfg')[source]#

Write a template config file with the current PLOT_CONFIG values.

Useful for users who want to tweak settings without touching Python code.

Parameters:

path (str or Path) – Destination file path. Default "pycsamt_plot.cfg" writes to the current working directory.

Returns:

The file that was written.

Return type:

Path

Examples

>>> write_default_config()          # creates pycsamt_plot.cfg in CWD
>>> write_default_config("~/.pycsamt/plot.cfg")   # user-global config