spectral_elbow_markers#
- spectral_elbow_markers(x, labels=None, *, y, h, label_shift=None, elbow_frac=0.5, half_elbow_gap=_Unset.UNSET, ax=None, 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 one elbow marker per spectral line, with the label displaced in x.
Each marker is a path from the tip at
yvertically toy + elbow_frac * h, horizontally bylabel_shift, then vertically toy + h(label anchor). Withelbow_frac=1the path is an L: the horizontal run sits aty + hand the label is placed beside its end.- Parameters:
x (float | Quantity | Sequence[float | Quantity]) – Line positions. Scalar is a single line.
labels (str | Sequence[str | None] | None, optional, default=None) – Scalar is broadcast; a sequence has length 1 or
len(x).None,'', whitespace-only and'none'(case-insensitive) mark a line as unlabeled: drawn, but not annotated.y (float | Quantity | Sequence[float | Quantity]) – Data y-coordinate of the tips. Scalar is broadcast; a sequence has length 1 or
len(x).Quantityis used as its bare value.h (float | Quantity | Sequence[float | Quantity]) – Signed marker height in data units; the label anchor sits at
y + h(h > 0: above the tips). Nonzero. Same handling asy. Increase|h|across neighboring lines to stagger labels.label_shift (float | Quantity | Sequence[float | Quantity | None] | None, optional, default=None) – Signed x displacement of the label anchor in x data units. Scalar is broadcast; a sequence has length 1 or
len(x).Nonemeans no shift.Quantityis converted tounitif given, without equivalencies.elbow_frac (float | Sequence[float], optional, default=0.5) – Fraction of
hat which the horizontal run sits. Scalar is broadcast; a sequence has length 1 orlen(x). Each value in (0, 1];1selects the half-elbow (L) for that line.ax (matplotlib.axes.Axes | None, optional, default=None) – Target axes. If
None, usesplt.gca().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: one color per line iflen(color) == len(x)(verbatim); otherwise a palette assigned to unique labels, cycled or cropped.
If
_UNSET, usesconfig.axline.color.unlabeled_color (ColorType | _Unset, optional, default=_UNSET) – Color of unlabeled lines when
coloris a colorset or palettelist; ignored otherwise. If_UNSET, usesconfig.spectral_line_marker.unlabeled_color.linewidth (float | list[float] | _Unset, optional, default=_UNSET) – Scalar or per-line width. If
_UNSET, usesconfig.spectral_line_marker.linewidth.linestyle (LineStyleType | list[LineStyleType] | _Unset, optional, default=_UNSET) – Scalar or per-line style. If
_UNSET, usesconfig.spectral_line_marker.marker_linestyle.alpha (float | list[float] | _Unset, optional, default=_UNSET) – Scalar or per-line marker alpha (not applied to text). If
_UNSET, usesconfig.axline.alpha.unit (astropy.units.UnitBase | None, optional, default=None) – Unit to convert
xandlabel_shiftto. IfNone,Quantityvalues are used as bare values.equivalencies (astropy.units.Equivalency | None, optional, default=None) – Equivalencies for the conversion of
x.fontsize (float | _Unset, optional, default=_UNSET) – Label font size. If
_UNSET, usesconfig.fontsizes.resolve('text').rotation (float | _Unset, optional, default=_UNSET) – Label rotation in degrees (CCW positive). If
_UNSET, usesconfig.spectral_line_marker.label_rotation.rotation_mode ({'default', 'anchor'} | _Unset, optional, default=_UNSET) –
Matplotlib
rotation_mode.'default': rotate, then align the bbox withha/va.'anchor': align withha/va, then rotate about the pinned point.
If
_UNSET, usesconfig.spectral_line_marker.label_rotation_mode.ha ({'left', 'center', 'right'} | _Unset, optional, default=_UNSET) – Horizontal label alignment. If
_UNSET, usesconfig.spectral_line_marker.label_ha; for half-elbows with nonzerolabel_shift,'left'if positive,'right'if negative.va ({'top', 'bottom', 'center', 'baseline'} | _Unset, optional, default=_UNSET) – Vertical label alignment (
'top': text hangs below the anchor). If_UNSET,'bottom'ifh > 0else'top'; for half-elbows with nonzerolabel_shift,'center'.label_offset_points (tuple[float, float] | _Unset, optional, default=_UNSET) –
Signed
(dx, dy)label shift in points, applied after anchoring.+dxis right and+dyis up, independent ofha,vaandrotation. If_UNSET:dxisconfig.spectral_line_marker.marker_label_offset_points[0], anddyfollowsva('top': -4,'bottom'/'baseline': 4,'center': 0).half-elbows with nonzero
label_shift:(sign(label_shift) * half_elbow_gap, 0).
half_elbow_gap (float | _Unset, optional, default=_UNSET) – Gap in points between the end of the horizontal run and the label for half-elbows with nonzero
label_shift. Magnitude only; direction followssign(label_shift). Ignored iflabel_offset_pointsis given. If_UNSET, usesconfig.spectral_line_marker.half_elbow_label_gap.label_kw (Mapping[str, Any] | None, optional, default=None) – Extra keyword arguments for
ax.annotate; override label defaults.**kwargs – Forwarded to
matplotlib.collections.LineCollection. Do not passcolors,linewidthsorlinestyles.
- Returns:
markers (list[matplotlib.collections.LineCollection]) – One per line, in input order.
annotations (list[matplotlib.text.Annotation]) – One per labeled line, in input order.
Overview#
Labels known spectral lines with one elbow marker per line. Pass line positions
and labels as parallel sequences. Each marker is a path from the tip at y to
the label anchor at y + h, with the label displaced in x by label_shift.
Use it to separate crowded labels that cannot share a connector.
Marker Geometry#
y and h are required. y is the data coordinate of the tips and h is the
signed marker height: the label anchor sits at y + h, above the tips for h > 0 and
below for h < 0. h must be nonzero. Both accept a scalar, applied to every line, or a
sequence with one value per line. Quantity values are used as their bare values and are
never converted, so y and h must share units.
The path is controlled by:
label_shiftis the signed x displacement of the label anchor, in x data units. It sets the length of the horizontal run.Nonemeans no shift, giving a straight vertical line.elbow_fracis the fraction ofhat which the horizontal bar sits, in [0, 1]. Scalar or one value per line.elbow_frac=1gives a half-elbow (L-shaped) marker: the bar sits aty + hand the label is placed beside its end instead of above it.Increase
|h|across neighboring lines to stagger labels.
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.4, 2.0, 1.8, 1.5, 1.2]
line_waves = [4634.140, 4640.640, 4641.850, 4647.420, 4651.470]
labels = ['N III', 'N III', 'N III', 'C III', 'C 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.03*u.Jy
plt.style.use(['full', 'stix'])
va.config.show_type_label = True
fig, ax = va.subplots(figsize=(7,7))
va.plot_spectrum(spectrum, figsize=(12,6), color='dark verdigris')
va.spectral_elbow_markers(
line_waves, labels,
y=y_vals,
h=[0.13, 0.1, 0.25, 0.3, 0.1],
label_shift=[0.2, -0.8, 2, 0.8, -1],
elbow_frac=[0.5, 1, 0.2, 0.8, 0.5],
)
va.set_limits(ylim=(0.75, 3.3), xlim=(4630, 4655))
plt.show()
(Source code, svg)
Half-Elbow Markers#
With elbow_frac=1 and nonzero label_shift, label defaults change:
hais'left'for positive shift and'right'for negative.vais'center'.label_offset_pointsis(sign(label_shift) * half_elbow_gap, 0).half_elbow_gapsets the gap in points between the run and the label. Magnitude only.Explicit
ha,vaandlabel_offset_pointstake precedence.Full and half elbows can be mixed in one call by passing
elbow_fracas a sequence.
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.03*u.Jy
plt.style.use(['full', 'libertinus'])
va.config.show_type_label = True
fig, ax = va.subplots(figsize=(12,5))
va.plot_spectrum(spectrum, figsize=(12,6), color='aurora green')
va.spectral_elbow_markers(
line_waves, labels, y=y_vals,
h=0.11,
label_shift=[0, 0.6, -0.5, 0.4, -0.9, 1, 1.5],
elbow_frac=[0.5, 1, 1, 0.5, 0.5, 0.1, 0.7],
)
va.set_limits(ylim=(0.75, 3.3))
plt.show()
(Source code, svg)
Label Placement#
Label text placement is further controlled by:
haandvaselect which point of the text bounding box is pinned to the anchor. For example,va='top'makes the text hang below the anchor.rotationsets the label angle in degrees (counter-clockwise).rotation_modesets the order of rotation and alignment. With'default', the text is rotated first and the rotated bounding box is then aligned viahaandva. With'anchor', the text is aligned first and then rotated about the pinned point, so the pin stays fixed at any angle.label_offset_pointsis a signed(dx, dy)shift in points, applied after anchoring. Positivedxmoves the label right and positivedymoves it up, regardless ofha,vaorrotation.
Changing the Color#
color accepts a single color, a VisualAstro colorset, or a list of colors.
A colorset, or a list whose length differs from the number of lines, is a palette
assigned to the unique labels in order of first appearance. It is cycled or cropped as
needed, so lines with identical labels always share a color. A list with exactly one
color per line is used as given, without grouping. The label text inherits the color of
its line.
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
rng = np.random.default_rng(13)
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]']
sigmas = [0.35, 0.25, 0.30, 0.30, 0.45, 0.40, 0.35]
gaussians = [models.Gaussian1D(A, mu, s) for A, mu, s in zip(amplitudes, line_waves, sigmas)]
x = np.linspace(4625, 4665, 500)
y = (
1.0 - 1e-2 * (x - 4645)
+ models.Gaussian1D(-0.3, 4645, 4.0)(x)
+ sum(g(x) for g in gaussians)
+ rng.normal(0.0, 0.08, x.shape)
)
spectrum = Spectrum(flux=y * u.Jy, spectral_axis=x * u.AA)
# peak height
y_vals = np.interp(line_waves * u.AA, spectrum.spectral_axis, spectrum.flux) + 0.03 * u.Jy
plt.style.use(['full', 'libertinus'])
fig, ax = va.subplots(figsize=(7,7))
va.plot_spectrum(spectrum, color='viridian')
va.spectral_elbow_markers(
line_waves, labels, y=y_vals, h=0.11,
label_shift=[0, -0.8, 1, 1.8, 0.0, 1, -1.5],
elbow_frac=[0.5, 1, 0, 0.5, 0.0, 0.1, 0],
color=['A train', 'borscht', 'ethernet green', '7 train'],
rotation=90,
label_offset_points=(2,3) # x, y offset
)
va.set_limits(ylim=(0.4, 3.3))
plt.show()
(Source code, svg)