jwspecfit.plotting

Publication-quality visualisation of spectral fits.

Functions

plot_2d_1d(path[, z, sci_ext, hdu, ...])

Plot a JWST/NIRSpec 2D + 1D spectrum from a .spec.fits file.

plot_fit(result, *[, fig, wave_unit, ...])

Plot a spectral fit with data, model, continuum, and residuals.

plot_fit_interactive(result, *[, wave_unit, ...])

Interactive plotly plot of a spectral fit with zoom and hover.

plot_spectrum_interactive(source, *[, z, ...])

Open and interactively plot one or more 1-D spectra.

jwspecfit.plotting.plot_2d_1d(path, z=None, *, sci_ext='SCI', hdu=None, wave_col=None, flux_col=None, err_col=None, flux_scale=1000.0, flux_label='$F_\\\\nu$ [nJy]', xlabel='$\\\\lambda_{\\\\rm obs}\\\\,[\\\\mu{\\\\rm m}]$', cmap='Blues', vmin_pct=5.0, vmax_pct=99.5, y_crop=(0.25, 0.75), xlim=None, ylim=None, line_colour='steelblue', line_width=0.5, err_colour='grey', err_alpha=0.35, figsize=(8, 4), dpi=300, title=None, lines=None, add_lines=None, height_ratios=(0.35, 1.0))[source]

Plot a JWST/NIRSpec 2D + 1D spectrum from a .spec.fits file.

Reads the 2D image from sci_ext and the 1D extraction from SPEC1D via jwspecfit.read_fits(), then renders a stacked figure (2D pcolormesh above, 1D flux below) with optional emission- line markers at the supplied redshift.

Parameters:
  • path (str | Path) – Path to the .spec.fits file.

  • z (float | None) – Redshift used to place observed-frame line markers. If None, no markers are drawn.

  • sci_ext (str) – Name of the 2D image extension (default "SCI").

  • hdu (str | int | None) – Forwarded to read_fits() for 1D extraction (override the default SPEC1D / column auto-detection).

  • wave_col (str | None) – Forwarded to read_fits() for 1D extraction (override the default SPEC1D / column auto-detection).

  • flux_col (str | None) – Forwarded to read_fits() for 1D extraction (override the default SPEC1D / column auto-detection).

  • err_col (str | None) – Forwarded to read_fits() for 1D extraction (override the default SPEC1D / column auto-detection).

  • flux_scale (float) – Multiplier and y-axis label applied to the 1D flux (default converts µJy → nJy).

  • flux_label (str) – Multiplier and y-axis label applied to the 1D flux (default converts µJy → nJy).

  • xlabel (str) – Shared x-axis label (default observed wavelength in µm).

  • cmap (str) – Colormap for the 2D panel.

  • vmin_pct (float) – Percentile clip for the 2D colour scale.

  • vmax_pct (float) – Percentile clip for the 2D colour scale.

  • y_crop (tuple[float, float]) – (y_lo_frac, y_hi_frac) fractional crop of the 2D vertical extent (default keeps the middle 50 % rows).

  • xlim (tuple[float, float] | None) – Optional axis limits. xlim applies to both panels.

  • ylim (tuple[float, float] | None) – Optional axis limits. xlim applies to both panels.

  • line_colour (str) – Colour and line width of the 1D flux trace.

  • line_width (float) – Colour and line width of the 1D flux trace.

  • err_colour (str) – Fill colour and alpha for the ±1σ error band.

  • err_alpha (float) – Fill colour and alpha for the ±1σ error band.

  • figsize (tuple[float, float]) – Matplotlib figure size, resolution (default 300), and 2D-vs-1D height ratio.

  • dpi (float) – Matplotlib figure size, resolution (default 300), and 2D-vs-1D height ratio.

  • height_ratios (tuple[float, float]) – Matplotlib figure size, resolution (default 300), and 2D-vs-1D height ratio.

  • title (str | None) – Optional title placed above the 2D panel.

  • lines (list[str] | bool | None) – Default-marker control: None uses the package defaults; a list of REST_LINES_A keys restricts to those names; False disables defaults entirely.

  • add_lines (list[str] | dict[str, float] | None) – Extra markers: either REST_LINES_A keys, or a {label: rest_wavelength_A} dict.

Returns:

Matplotlib figure and the two axes.

Return type:

fig, (ax_2d, ax_1d)

jwspecfit.plotting.plot_fit(result, *, fig=None, wave_unit='A', flux_unit='fnu', show_residuals=True, show_components=True, label_lines=True, y_pad=1.3, exclude_wave_A=None, rest_frame=False, save_path=None)[source]

Plot a spectral fit with data, model, continuum, and residuals.

The y-axis upper limit is set to the peak of the tallest emission line (above continuum) times y_pad, so the plot is scaled to the lines rather than noise spikes.

Parameters:
  • result (FitResult) – Output of fit_lines().

  • fig (Figure, optional) – Matplotlib figure to draw on. If None, creates a new one.

  • wave_unit (str) – "A" for Angstroms (default) or "um" for microns.

  • flux_unit (str) – "fnu" for µJy (default) or "flam" for erg/s/cm²/Å.

  • show_residuals (bool) – Show residual panel below the main plot (default True).

  • show_components (bool) – Show individual Gaussian components as filled curves (default True). Broad components are drawn with hatching for clarity.

  • label_lines (bool) – Annotate line identifications (default True).

  • y_pad (float) – Multiplicative padding above the tallest line peak (default 1.3).

  • exclude_wave_A (list of (float, float), optional) – Wavelength ranges in Angstroms to hide from the plot. Each tuple is (lo, hi). Useful for masking noisy detector regions.

  • rest_frame (bool) – If True, plot wavelengths in the rest frame by dividing by (1 + z) using the redshift stored in the spectrum. Default False (observed frame).

  • save_path (str, optional) – If given, save the figure to this file path (e.g. "fit.pdf").

Returns:

The matplotlib figure.

Return type:

Figure

jwspecfit.plotting.plot_fit_interactive(result, *, wave_unit='A', flux_unit='fnu', show_components=True, show_residuals=True, y_pad=1.3, exclude_wave_A=None, rest_frame=False, z=None, lines=False, add_lines=None, line_color='darkred', show_2d='auto', cmap_2d='Blues', vmin_pct=5.0, vmax_pct=99.5, y_crop=(0.25, 0.75))[source]

Interactive plotly plot of a spectral fit with zoom and hover.

Optionally stacks a 2-D rectified-spectrum panel above the main fit panel (when result.spectrum.sci_2d is populated by read_fits()) and a residual panel below. By default no curated emission-line markers are drawn — every fitted line is already labelled at its peak above the model. Pass lines=None to add the package-default markers, or an explicit list of jwspecfit.lines.REST_LINES_A keys to mark only those.

Parameters:
  • result (FitResult) – Output of fit_lines().

  • wave_unit (str) – "A" for Angstroms (default) or "um" for microns.

  • flux_unit (str) – "fnu" for µJy (default) or "flam" for erg/s/cm²/Å.

  • show_components (bool) – Show individual line components (default True).

  • show_residuals (bool) – Show residual panel below the main plot (default True).

  • y_pad (float) – Multiplicative padding above tallest line (default 1.3).

  • exclude_wave_A (list of (float, float), optional) – Wavelength ranges in Angstroms to hide from the plot.

  • rest_frame (bool) – If True, plot wavelengths in the rest frame by dividing by (1 + z). Default False (observed frame). Emission-line markers are placed at rest wavelengths when True.

  • z (float, optional) – Redshift override used for rest-frame conversion and marker placement. When None (default), result.spectrum.z is used. Raises ValueError if rest_frame=True and neither source provides a redshift.

  • lines (sequence of str, bool, or None) – Curated emission-line markers (vertical dashed lines + labels). False (default) draws none — the fit-component peak annotations already identify every fitted line. None opts in to the package-default marker set; an explicit list of jwspecfit.lines.REST_LINES_A keys marks only those names.

  • add_lines (dict[str, float] or sequence of str, optional) – Extra markers to overlay on top of lines. Same semantics as in plot_spectrum_interactive().

  • line_color (str) – Colour for the emission-line markers and their labels (default "darkred").

  • show_2d (bool or {"auto"}) – Whether to stack the 2-D rectified spectrum image above the fit panel. "auto" (default) shows it iff result.spectrum.sci_2d is populated. True forces it (silently no-ops when no 2-D is available); False always hides it.

  • cmap_2d (str) – Plotly colorscale for the 2-D panel (default "Blues").

  • vmin_pct (float) – Percentile clip for the 2-D colour scale (default 5 / 99.5).

  • vmax_pct (float) – Percentile clip for the 2-D colour scale (default 5 / 99.5).

  • y_crop ((float, float)) – Fractional crop (lo, hi) of the spatial axis on the 2-D panel (default (0.25, 0.75)).

Return type:

plotly.graph_objects.Figure

jwspecfit.plotting.plot_spectrum_interactive(source, *, z=None, wave_unit='A', flux_unit='fnu', rest_frame=False, exclude_wave_A=None, title=None, labels=None, lines=None, add_lines=None, line_color='darkred', show_zero=True, show_2d='auto', cmap_2d='Blues', vmin_pct=5.0, vmax_pct=99.5, y_crop=(0.25, 0.75), **read_kwargs)[source]

Open and interactively plot one or more 1-D spectra.

Accepts a Spectrum object, a path to a .fits / .npz file, or a list / tuple of such items. When given a path, the file is read via read_fits() (or read_npz() for .npz) and any extra read_kwargs are forwarded to the reader (e.g. hdu=, wave_col= for FITS overrides).

Parameters:
  • source (Spectrum, str, Path, or sequence of these) – A single spectrum / file path, or a list / tuple of them to overplot.

  • z (float, optional) – Source redshift. Used only when a source item is a path; for an existing Spectrum, its own z is preserved. Forwarded to every reader call.

  • wave_unit (str) – "A" for Angstroms (default) or "um" for microns.

  • flux_unit (str) – "fnu" for µJy (default) or "flam" for erg/s/cm²/Å.

  • rest_frame (bool) – If True and a spectrum has a redshift, divide wavelengths by (1 + z). Default False (observed frame). Applied per spectrum.

  • exclude_wave_A (list of (float, float), optional) – Wavelength ranges in Angstroms to hide from the plot.

  • title (str, optional) – Figure title. When a single spectrum is supplied, defaults to filename + redshift + grating if available; when multiple spectra are supplied, defaults to no title.

  • labels (str or sequence of str, optional) – Legend label(s). When None (default), a single spectrum uses "Data" and multiple spectra use each spectrum’s filename (or "Spectrum {i}" as a fallback).

  • lines (sequence of str, bool, or None) – Emission lines to mark as vertical dashed lines at the supplied redshift. None (default) draws a curated list of common UV/optical lines. Pass an explicit list of keys from jwspecfit.lines.REST_LINES_A to override, or False to disable. The effective redshift is taken from z if given, else from a single spectrum’s own spec.z. In rest-frame mode the markers sit at the rest wavelengths.

  • add_lines (dict[str, float] or sequence of str, optional) –

    Extra lines to overlay on top of lines. Two accepted forms:

    • dict{label: rest_wavelength_A}. Free-form labels with explicit rest-frame wavelengths in Angstroms. Use this for lines not in jwspecfit.lines.REST_LINES_A, e.g. add_lines={"Mg II 2796": 2796.352}.

    • list of str — names from REST_LINES_A (e.g. add_lines=["H8", "HEPSILON", "FeII_2382"]). The rest wavelength is looked up automatically. Call jwspecfit.show_lines() to see what’s available.

    Each entry is redshifted by (1 + z) and staggered alongside the default markers.

  • line_color (str) – Colour for the emission-line markers and their labels (default "darkred").

  • show_zero (bool) – Draw a light-grey dashed horizontal line at y = 0 to make continuum detection easier to gauge by eye (default True).

  • show_2d (bool or {"auto"}) – Whether to render the 2-D rectified spectrum image above the 1-D panel. "auto" (default) shows it iff a single spectrum is supplied and its sci_2d is populated (e.g. when read from an msaexp .spec.fits file). True forces it (silently no-ops when multiple spectra are supplied or no 2-D is available); False always shows the 1-D only. The two panels share the wavelength axis; emission-line markers span both.

  • cmap_2d (str) – Plotly colorscale for the 2-D panel (default "Blues" to mirror plot_2d_1d()).

  • vmin_pct (float) – Percentile clip for the 2-D colour scale (default 5 / 99.5).

  • vmax_pct (float) – Percentile clip for the 2-D colour scale (default 5 / 99.5).

  • y_crop ((float, float)) – Fractional crop (lo, hi) of the spatial axis on the 2-D panel (default (0.25, 0.75) keeps the middle 50 % of rows).

  • **read_kwargs – Forwarded to the file reader when a source item is a path.

Return type:

plotly.graph_objects.Figure