spectral_markers#

spectral_markers(x, labels=None, *, y, h, ax=None, group=True, connector=True, connector_extend=None, stem=None, label_loc=_Unset.UNSET, color=_Unset.UNSET, unlabeled_color=_Unset.UNSET, linewidth=_Unset.UNSET, linestyle=_Unset.UNSET, alpha=_Unset.UNSET, unit=None, equivalencies=None, fontsize=_Unset.UNSET, rotation=_Unset.UNSET, rotation_mode=_Unset.UNSET, ha=_Unset.UNSET, va=_Unset.UNSET, label_offset_points=_Unset.UNSET, label_kw=None, **kwargs)[source]#

Plot prong markers at spectral line positions with optional labels.

Each marker is a set of vertical prongs from y to y + h, joined by a horizontal connector at y + h. Lines sharing a label are drawn as one multi-prong marker. An optional vertical stem links the connector to the label.

Parameters:
  • x (float | astropy.units.Quantity | Sequence[float | astropy.units.Quantity]) – Line positions. A scalar is treated as a single line.

  • labels (str | Sequence[str | None] | None, optional, default=None) –

    • str: broadcast to every line.

    • sequence: one entry per line (length 1 or len(x)).

    • None: no labels.

    None, '', whitespace-only strings and 'none' (case-insensitive) mark a line as unlabeled. Unlabeled lines get no annotation and are never grouped.

  • y (float | astropy.units.Quantity | Sequence[float | astropy.units.Quantity]) – Data y-coordinate of the prong tips. Scalar is broadcast; a sequence has length 1 or len(x). Quantity values are used as their bare values, without conversion.

  • h (float | astropy.units.Quantity | Sequence[float | astropy.units.Quantity]) – Signed marker height in data units. The connector sits at y + h: h > 0 places it above the tips, h < 0 below. Must be nonzero. Same broadcasting and unit handling as y.

  • ax (matplotlib.axes.Axes | None, optional, default=None) – Axes on which to draw. If None, uses plt.gca().

  • group (bool, optional, default=True) – If True, lines sharing a label form one marker with a single label. If False, every line is its own marker and is labeled individually.

  • connector (bool, optional, default=True) – If False, only the prongs are drawn and connector_extend and stem are ignored. The connector is drawn only if its length is positive.

  • connector_extend (ConnectorExtendType | None, optional, default=None) – Extension of the connector beyond the outermost prongs, in x data units. A scalar extends both sides; a tuple is (left, right). Quantity values are converted to unit if given, without equivalencies.

  • stem (float | astropy.units.Quantity | None, optional, default=None) – Length of a vertical segment from the connector anchor to the label, in y data units. The stem is drawn at the label anchor x (see label_loc), points away from the tips (direction sign(h)) and moves the label anchor to y + h + sign(h) * stem. Drawn only for labeled markers and only where a connector is drawn (connector=True and positive connector length). None``and ``0 draw no stem. Same unit handling as y and h.

  • label_loc ({'left', 'center', 'right'} | _Unset, optional, default=_UNSET) – Position of the label anchor along the connector extent (including connector_extend). If _UNSET, uses config.spectral_line_marker.label_ha.

  • color (ColorType | str | list[ColorType] | _Unset, optional, default=_UNSET) –

    Color of markers and label text. Lines with identical labels share a color.

    • single color (str | RGB(A) tuple): all markers.

    • colorset alias (str): palette assigned to unique labels in order of first appearance, cycled or cropped.

    • list | numpy.ndarray:

      • len(color) == len(x): one color per line, used verbatim. Identical labels are not grouped.

      • otherwise: palette assigned to unique labels, cycled if shorter than the number of unique labels and cropped if longer. Identical labels share a color.

    A marker uses the color of its first line. If _UNSET, uses config.axline.color.

  • unlabeled_color (ColorType | _Unset, optional, default=_UNSET) – Color of unlabeled lines when color is a colorset or a palette list. Ignored if color is a single color or a per-line list. If _UNSET, uses config.spectral_line_marker.unlabeled_color.

  • linewidth (float | list[float] | _Unset, optional, default=_UNSET) – Scalar or per-line (list) width. A marker uses the value of its first line. If _UNSET, uses config.spectral_line_marker.linewidth.

  • linestyle (LineStyleType | list[LineStyleType] | _Unset, optional, default=_UNSET) – Scalar or per-line (list) style. A marker uses the value of its first line. If _UNSET, uses config.spectral_line_marker.marker_linestyle.

  • alpha (float | list[float] | _Unset, optional, default=_UNSET) – Scalar or per-line (list) alpha of the markers (not applied to label text). A marker uses the value of its first line. If _UNSET, uses config.axline.alpha.

  • unit (astropy.units.UnitBase | None, optional, default=None) – Unit to convert x and connector_extend to. If None, Quantity values are used as their bare values, without conversion.

  • equivalencies (astropy.units.Equivalency | None, optional, default=None) – Equivalencies used in the unit conversion of x.

  • fontsize (float | _Unset, optional, default=_UNSET) – Label font size. If _UNSET, uses config.fontsizes.resolve('text').

  • rotation (float | _Unset, optional, default=_UNSET) – Label rotation in degrees (positive turns CCW). If _UNSET, uses config.spectral_line_marker.label_rotation.

  • rotation_mode ({'default', 'anchor'} | _Unset, optional, default=_UNSET) –

    Rotation order for the label (matplotlib rotation_mode).

    • 'default': rotate the text, then align its bbox with ha and va.

    • 'anchor': align with ha and va, then rotate about the pinned point.

    If _UNSET, uses config.spectral_line_marker.label_rotation_mode.

  • ha ({'left', 'center', 'right'} | _Unset, optional, default=_UNSET) – Horizontal alignment of the label. Selects which point of the text bbox is pinned to the anchor plus offset. If _UNSET, equals label_loc.

  • va ({'top', 'bottom', 'center', 'baseline'} | _Unset, optional, default=_UNSET) – Vertical alignment of the label. Selects which point of the text bbox is pinned to the anchor plus offset ('top': text hangs below the anchor). If _UNSET, 'bottom' when h > 0 and 'top' otherwise, so the label sits outside the marker.

  • label_offset_points (tuple[float, float] | _Unset, optional, default=_UNSET) – Signed (dx, dy) shift of the label in points, applied after anchoring. Positive dx moves right, positive dy moves up, independent of ha, va and rotation. If _UNSET, dx is config.spectral_line_marker.marker_label_offset_points[0] and dy is chosen from va ('top': -4, 'bottom' and 'baseline': 4, 'center': 0).

  • label_kw (Mapping[str, Any] | None, optional, default=None) – Extra keyword arguments for ax.annotate. Override label defaults.

  • **kwargs – Forwarded to matplotlib.collections.LineCollection.

Returns:

  • markers (list[matplotlib.collections.LineCollection]) – One per marker (group), in order of first appearance.

  • annotations (list[matplotlib.text.Annotation]) – One per labeled marker, in the same order.

Overview#

Allows for automated labeling of known spectral lines. Pass the line positions and labels as parallel sequences, use y to control the position of the labels and h to control the height of the prong markers.

Marker Geometry#

y and h are required. y is the data coordinate of the prong tips and h is the signed marker height: the connector sits at y + h, above the tips for h > 0 and below for h < 0. h must be nonzero. Both accept a scalar, which is applied to every line, or a sequence with one value per line, e.g. fitted peak amplitudes plus an offset. Quantity values are used as their bare values and are never converted, so y and h must share units.

import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np
from astropy.modeling import models
from specutils import Spectrum

import visualastro as va

np.random.seed(42)
amplitudes = [1.6, 2.0, 1.5, 1.5, 1.2, 1.7, -1.1]
line_waves = [4634.140, 4640.640, 4641.850, 4647.420, 4651.470, 4711.260, 4740.120]
labels = ['N III', 'N III', 'N III', 'C III', 'C III', '[Ar IV]', '[Ar IV]',]
gaussians = [models.Gaussian1D(A, mu, 0.2) for (A, mu) in zip(amplitudes, line_waves)]

x = np.linspace(4620, 4760, 500)
y = (1.0 + 2e-4 * (x - 4500) + sum(g(x) for g in gaussians) + np.random.normal(0.0, 0.1, x.shape))
spectrum = Spectrum(flux=y * u.Jy, spectral_axis=x * u.AA)

# create figure

plt.style.use(['full', 'concrete-bold'])
fig, ax = va.subplots(figsize=(12,6))
va.plot_spectrum(spectrum, color='violetred', xlabel=r'Wavelength', ylabel=r'Flux')

# 3 prong marker
va.spectral_markers(line_waves[:3], labels[:3], y=2.7, h=0.2)
# 2 prong marker with a stem
va.spectral_markers(line_waves[3:5], labels[3:5], y=2.51, h=0.2, stem=0.1)
# single marker pointing down
va.spectral_markers(line_waves[5], labels[5], y=2.6, h=0.1)
# single marker pointing up
va.spectral_markers(line_waves[6], labels[6], y=0.0, h=-0.1)

va.set_limits(ylim=(-0.5, 3.35))

plt.show()

(Source code, svg)

../../../_images/plot_spectral_markers_basic.svg

The connector and the label leader are controlled by:

  • connector=False draws only the prongs. With a scalar x this gives a single prong with a label.

  • connector_extend extends the connector beyond the outermost prongs, in x data units. A scalar extends both sides and a tuple is (left, right). It is ignored if connector=False. The connector is drawn only if its length is positive, so a single line has no connector unless it is extended.

  • stem adds a vertical segment from the connector to the label, in y data units. It points away from the tips (the direction of sign(h)) and is drawn at the label anchor, so it follows label_loc. It applies to labeled markers only and is drawn only where a connector is drawn, so a single line needs a positive connector_extend

import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np
from astropy.modeling import models
from specutils import Spectrum

import visualastro as va

np.random.seed(42)
amplitudes = [1.1, 1.4, 2.0, 1.5, 1.5, 1.2, 0.97]
line_waves = [4629.339, 4634.140, 4640.640, 4641.850, 4647.420, 4651.470, 4658.050]
labels = ['Fe II', 'N III', 'N III', 'N III', 'C III', 'C III', '[Fe III]']
y_vals = [2.33, 2.73, 3.15, 3.15, 2.6, 2.6, 2.2]
gaussians = [models.Gaussian1D(A, mu, 0.2) for (A, mu) in zip(amplitudes, line_waves)]

x = np.linspace(4625, 4665, 500)
y = (1.0 + 2e-4 * (x - 4500) + sum(g(x) for g in gaussians) + np.random.normal(0.0, 0.1, x.shape))
spectrum = Spectrum(flux=y * u.Jy, spectral_axis=x * u.AA)

# create figure

plt.style.use(['full', 'stix'])
fig, ax = va.subplots(figsize=(12,6))
va.plot_spectrum(spectrum, color='7 train', xlabel=r'Wavelength', ylabel=r'Flux')

# single prong with a symmetric connector extension
va.spectral_markers(
    line_waves[0], labels[0], y=y_vals[0], h=0.1,
    connector_extend=0.5,
)

# single prong with an asymmetric connector extension
va.spectral_markers(
    line_waves[1], labels[1], y=y_vals[1], h=0.1,
    connector_extend=(0, 1.5),
    ha='center',
)

# two-line group, prongs only
va.spectral_markers(
    line_waves[2:4], labels[2:4], y=y_vals[2:4], h=0.07,
    connector=False,
    stem=0.05,
)

# two-line group with a stem, plus one single line without stem
va.spectral_markers(
    line_waves[4:], labels[4:], y=y_vals[4:], h=0.07,
    stem=0.05,
)

va.set_limits(ylim=(0.5, 3.5))

plt.show()

(Source code, svg)

../../../_images/plot_spectral_markers_connector.svg

Disabling Grouped Markers#

group=False disables grouping, so every line is drawn as its own marker and is labeled individually, even when labels repeat.

This is useful if you have individual peak heights of the spectra from fitting. With group=False:

  • Each line gets its own prong, label and, if connector_extend is given, its own connector bar. Pass a sequence to configure each marker independently.

  • Repeated labels are drawn once per line.

  • stem has no effect, because it applies only to markers with more than one line. Increase h to raise the label instead.

  • color, linewidth, linestyle and alpha apply per line. VisualAstro colorsets are supported.

import astropy.units as u
import matplotlib.pyplot as plt
import numpy as np
from astropy.modeling import models
from specutils import Spectrum

import visualastro as va

np.random.seed(0)
amplitudes = [1.1, 1.4, 2.0, 1.5, 1.5, 1.2, 0.97]
line_waves = [4629.339, 4634.140, 4640.640, 4641.850, 4647.420, 4651.470, 4658.050]
labels = ['Fe II', 'N III', 'N III', 'N III', 'C III', 'C III', '[Fe III]']

gaussians = [models.Gaussian1D(A, mu, 0.2) for (A, mu) in zip(amplitudes, line_waves)]

x = np.linspace(4625, 4665, 500)
y = (
    1.0 + 2e-4 * (x - 4500)
    + sum(g(x) for g in gaussians)
    + np.random.normal(0.0, 0.05, x.shape)
)
spectrum = Spectrum(flux=y * u.Jy, spectral_axis=x * u.AA)

# calculate peak height
y_vals = np.interp(line_waves*u.AA, spectrum.spectral_axis, spectrum.flux) + 0.1*u.Jy

plt.style.use(['full', 'hershey'])
fig, ax = va.subplots(figsize=(12,6))
va.plot_spectrum(spectrum, color='twilight', xlabel=r'Wavelength', ylabel=r'Flux')

va.spectral_markers(
    line_waves, labels,
    y=y_vals, h=0.1,
    group=False,
    rotation=90,
    color='subway',
    lw=1.5,
    connector_extend=[0,0.5,(0,1),0.2,(1,0.3),0,0]
)

va.set_limits(ylim=(0.5, 3.7))

plt.show()

(Source code, svg)

../../../_images/plot_spectral_markers_ungrouped.svg

Label Placement#

Label text placement is further controlled by:

  • ha and va select which point of the text bounding box is pinned to the anchor. For example, va='top' makes the text hang below the anchor.

  • rotation sets the label angle in degrees (counter-clockwise).

  • rotation_mode sets the order of rotation and alignment. With 'default', the text is rotated first and the rotated bounding box is then aligned via ha and va. With 'anchor', the text is aligned first and then rotated about the pinned point, so the pin stays fixed at any angle.

  • label_offset_points is a signed (dx, dy) shift in points, applied after anchoring. Positive dx moves the label right and positive dy moves it up, regardless of ha, va or rotation.

See Also#