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:
Environment variables (highest precedence):
PYCSAMT_FMT="+svg,+pdf" PYCSAMT_DPI=300 python make_figures.py
PYCSAMT_FMTis a comma-separated list of format tokens (+prefix supported). Other variables:PYCSAMT_DPI,PYCSAMT_SAVEDIR,PYCSAMT_TRANSPARENT,PYCSAMT_BBOX.Config file (
pycsamt_plot.cfgin the working directory, or~/.pycsamt/plot.cfgas 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.
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 PDFA 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
Package-level singleton. |
Functions
|
Attach an axes-aligned colorbar with smart tick density. |
|
Attach a compact colorbar beside a polar axes. |
|
(Re-)load a config file into |
Reset |
|
|
Save a pyCSAMT figure using the global |
|
Set the global raster DPI on |
|
Set the global export format(s) on |
|
Set the global output directory on |
|
Write a template config file with the current |
Classes
|
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:
objectGlobal plot-export configuration singleton for pyCSAMT.
The module-level
PLOT_CONFIGinstance is the recommended entry point. Mutate it once (at the top of your script or notebook) and every subsequentsave_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. Use300–600for publication.bbox_inches (str, default
"tight") – Passed tosavefig().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) – Callplt.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→ usefmt.- Returns:
Clean format strings (no
+, no leading dot).- Return type:
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
savediris set, the path is resolved undersavedir.fmt (str, list[str], or None) – Per-call format override.
None→fmt.dpi (int or None) – Per-call DPI override.
None→dpi.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:
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
PlotConfigattribute by name.- Return type:
None
Examples
>>> PLOT_CONFIG.configure(fmt="+svg", dpi=300, savedir="~/figures")
- context(**kw)[source]#
Temporarily override config attributes, then restore.
- Parameters:
**kw (Any) – Any writable
PlotConfigattribute 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
- 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.
- 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.
- pycsamt.api.plot.save_fig(fig_or_ax, path, *, fmt=None, dpi=None, **kw)[source]#
Save a pyCSAMT figure using the global
PLOT_CONFIGsettings.- 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.
None→PLOT_CONFIG.fmt.dpi (int or None) – Per-call DPI override.
None→PLOT_CONFIG.dpi.**kw – Forwarded to
PlotConfig.save().
- Returns:
File paths written.
- Return type:
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_CONFIGto 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.Nonesearches the default locations (pycsamt_plot.cfgin 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_CONFIGvalues.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:
Examples
>>> write_default_config() # creates pycsamt_plot.cfg in CWD >>> write_default_config("~/.pycsamt/plot.cfg") # user-global config