set_limits#

set_limits(ax=None, *, limits=None, center=None, xlim=None, ylim=None, points=None, weights=None, xpad=_Unset.UNSET, ypad=_Unset.UNSET, recompute_other_axis=_Unset.UNSET, square=False)[source]#

Set the limits of a Matplotlib Axes.

If only one of xlim or ylim is provided, the limits of the other axis are recomputed from the data visible within the provided range. Matplotlib does not do this by itself. Call after all plotting calls.

Parameters:
  • ax (matplotlib.axes.Axes | None, optional, default=None) – Axes to modify. If None, uses the current Axes.

  • limits (float | tuple[float, float] | None, optional, default=None) –

    Window applied to both axes, relative to center (origin if None). Cannot be combined with xlim or ylim.

    • Scalar: (center - |limits|, center + |limits|).

    • tuple[float, float]: (center + lo, center + hi).

  • center (str | float | tuple[float, float] | Callable | None, optional, default=None) –

    Window center. Requires limits. None → origin.

    • 'origin', 'com', 'median': named modes. Data-dependent modes read points from points, or from non-connected artists on ax if points is None (unit masses).

    • Scalar or (cx, cy): explicit center.

    • Callable: fn(points, weights) -> (cx, cy).

  • xlim (tuple[float, float] | None, optional, default=None) – X-axis limits, applied as given (inverted limits invert the axis). If only one of xlim, ylim is provided and recompute_other_axis=True, the other axis limits are computed from the data visible within the provided range. If both are provided, no computation is done.

  • ylim (tuple[float, float] | None, optional, default=None) – Y-axis limits. See xlim.

  • points (np.ndarray | None, optional, default=None) – Array of shape (N, 2) used to compute the center. If None, uses the data on the ax instance.

  • weights (np.ndarray | None, optional, default=None) – Masses of shape (N,). Requires points. Ignored by 'median'.

  • xpad (float | None | _Unset, optional, default=_UNSET) – Fractional padding (finite, > -0.5). Applied via ax.margins when no limits are given, or to the computed X range when only ylim is given. Ignored if limits is given. None defaults to current margins.

  • ypad (float | None, optional, default=None) – Fractional padding of the computed Y-axis limits. Only used if xlim is provided without ylim. Otherwise behaves as xpad. If None, uses ax.margins()[1].

  • recompute_other_axis (bool | _Unset, optional, default=_UNSET) – If True and only one of xlim or ylim is provided, the limits of the other axis are computed from the data visible within the provided range. If False, only the provided limits are set and the other axis is autoscaled by Matplotlib. Ignored if limits is given or if both xlim and ylim are provided. If _UNSET, uses config.axes.recompute_other_axis.

  • square (bool, optional, default=False) – If True, make the X and Y ranges of ax equal by expanding the narrower one. Is ignored if limits is not None.

Returns:

xlim, ylim – Limits on ax after the call.

Return type:

tuple[float, float]

Raises:

ValueError – If limits is combined with xlim or ylim. If limits is not a scalar or a tuple[float, float]. If xpad or ypad is not finite or is <= -0.5.

Notes

  • If no limits are given, nothing is done.

  • Limits are interpreted in the units the data was plotted in.

  • Setting limits disables autoscaling on the affected axes.

Examples#

Window Clipping#

If recompute_other_axis=True, and xlim is passed without ylim (or vice-versa), VisualAstro will apply 1D box clipping onto the other axis. This rescales the unset axis by only taking into account the portion of the data visible in the window set by limit passed in. The effects are illustrated in the plot below.

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 = [0.4, 0.5, 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]
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.erg*u.cm**-2*u.s**-1, spectral_axis=x * u.AA)

plt.style.use('concrete')
va.config.show_type_label = False
fig, ax = va.subplots(1, 2, figsize=(12,5))

va.plot_spectrum(
    spectrum, ax=ax[0],
    color='abyssal',
    title='recompute_other_axis=False'
)
va.set_limits(ax=ax[0], xlim=(4625, 4640.34), recompute_other_axis=False)

va.plot_spectrum(
    spectrum, ax=ax[1],
    color='abyssal',
    title='recompute_other_axis=True'
)
va.set_limits(ax=ax[1], xlim=(4625, 4640.34), recompute_other_axis=True)

plt.show()

(Source code, svg)

../../../_images/plot_set_limits_recompute.svg

Symmetric Limits#

In addition to xlim and ylim, shared limits for both axes can be set with limits. The window is always interpreted relative to center (the origin if center is None).

  • Use a tuple (lo, hi) to set xlim=(center + lo, center + hi) and ylim=(center + lo, center + hi). With the default center this is xlim=ylim=(lo, hi). If lo > hi both axes are inverted.

  • Use a single float value to set a symmetric window xlim=ylim=(center - |value|, center + |value|).

limits cannot be combined with xlim or ylim, and a zero-width window raises a ValueError. Symmetric limits require linear axes, since a shifted window is not meaningful on a log scale. Axes that are already inverted (e.g. RA or magnitude) stay inverted unless the window itself is inverted.

import matplotlib.pyplot as plt

import visualastro as va

plt.style.use(['full', 'concrete'])
va.config.fontsizes.tick_labels = 0.87

blob1 = va.blob(5000, as_array=True)
blob2 = va.blob(2500, as_array=True)
blob1[:,0] += 5
blob2[:,1] -= 10


fig, ax = va.subplots(1, 2, figsize=(11,5))

va.scatter(blob1[:,0], blob1[:,1], ax=ax[0], s=0.1, color='Holy Red', title='limits=(-2,8)')
va.set_limits(ax=ax[0], limits=(-2, 8))

va.scatter(blob1[:,0], blob1[:,1], ax=ax[1], s=0.1, color='Holy Red', title='limits=15')
va.scatter(
    blob2[:,0], blob2[:,1], ax=ax[1],
    s=0.1, color='Holy Blue', grid=True,
    grid_color='blue', grid_ls=':', grid_alpha=0.5
)
va.set_limits(ax=ax[1], limits=15)

plt.show()

(Source code, svg)

../../../_images/plot_set_limits_symmetric.svg

Centering the Window#

The window can be moved with center, which requires limits. A scalar centers both axes at the same value, and a tuple (cx, cy) sets each axis independently.

  • center='origin' (the default) centers the window at (0, 0).

  • center='com' centers the window on the center of mass of the plotted points, assuming unit masses unless weights are given.

  • center='median' centers on the coordinate-wise median, which is more robust to outliers. weights are ignored.

  • A callable fn(points, weights) -> (cx, cy) can be passed for any custom center, such as the densest point or the most massive particle.

Data-dependent modes read their points from points if provided, and otherwise from the scatter and marker-only artists already drawn on the axes. Lines, patches, and filled regions are excluded, since their vertex count would bias the result. Call set_limits after all plotting calls, or pass points explicitly.

import matplotlib.pyplot as plt

import visualastro as va

plt.style.use(['full', 'concrete'])
va.config.fontsizes.tick_labels = 0.87
va.config.legend.markerscale = 15

blob1 = va.blob(5000, as_array=True)
blob2 = va.blob(2500, as_array=True)
blob1[:,0] += 5
blob2[:,1] -= 10


fig, ax = va.subplots(1, 3, figsize=(13,4))

va.scatter(blob1[:,0], blob1[:,1], ax=ax[0], s=0.1, color='Holy Red', label='Galaxy 1')
va.scatter(blob2[:,0], blob2[:,1], ax=ax[0], s=0.1, color='Holy Blue', label='Galaxy 2')
va.set_title("limits=10, center='com'", ax=ax[0])
va.set_limits(limits=10, ax=ax[0], center='com')

va.scatter(blob1[:,0], blob1[:,1], ax=ax[1], s=0.1, color='Holy Red', label='Galaxy 1')
va.scatter(blob2[:,0], blob2[:,1], ax=ax[1], s=0.1, color='Holy Blue', label='Galaxy 2')
va.scatter(-1000000, 0, ax=ax[1], s=0.1, label='Outlier')
va.set_title("limits=10, center='com'", ax=ax[1])
va.set_limits(limits=10, ax=ax[1], center='com')

va.scatter(blob1[:,0], blob1[:,1], ax=ax[2], s=0.1, color='Holy Red', label='Galaxy 1')
va.scatter(blob2[:,0], blob2[:,1], ax=ax[2], s=0.1, color='Holy Blue', label='Galaxy 2')
va.scatter(-10000, 0, ax=ax[2], s=0.1, title="center='median'", label='Outlier')
va.set_title("limits=10, center='median'", ax=ax[2])
va.set_limits(limits=10, ax=ax[2], center='median')

plt.show()

(Source code, svg)

../../../_images/plot_set_limits_recenter_window.svg

The points argument can be used to center around a subset of the data plotted. Here we center around the center of mass of only the second group.

import matplotlib.pyplot as plt

import visualastro as va

plt.style.use(['full', 'concrete'])
va.config.fontsizes.tick_labels = 0.87
va.config.legend.markerscale = 15

blob1 = va.blob(5000, as_array=True)
blob2 = va.blob(5000, as_array=True)
blob1[:,0] += 5
blob2[:,1] -= 10

dens = va.number_density(blob2[:,0:2], k=50)
va.scatter(blob1[:,0], blob1[:,1], s=0.1, color='Holy Red', title='limits=10')
va.scatter(
    blob2[:,0], blob2[:,1],
    s=0.1, c=dens, grid=True,
    grid_color='blue', grid_ls=':', grid_alpha=0.5
)
va.set_limits(limits=10, center='com', points=blob2[:,0:2])

plt.show()

(Source code, svg)

../../../_images/plot_set_limits_recenter_window_subset.svg

Square Limits#

Set square=True to make the numeric ranges of both axes equal. The narrower axis is expanded about its own center, so no data is cut off, and inverted axes stay inverted. This is ignored if limits is not None.

Squaring is applied last, after xlim, ylim, padding, and any recomputed limits, so it composes with every other option. If both xlim and ylim are given with different ranges, the narrower one is expanded and the requested limits are not preserved exactly.

Note

Equal ranges do not imply equal scaling on screen. On a non-square axes box, use ax.set_aspect('equal') for geometrically correct proportions.

import matplotlib.pyplot as plt
import numpy as np

import visualastro as va

plt.style.use(['minimal', 'stix'])

rng = np.random.default_rng(42)
n = 2000
x = rng.normal(0, 4, n)
y = rng.normal(0, 1, n)

fig, axs = plt.subplots(1, 2, figsize=(8, 4))

for ax, square in zip(axs, (False, True)):
    va.scatter(x, y, ax=ax, s=2, color='nebula', transform='saturate', factor=0.9)
    va.set_limits(ax, xlim=(-10, 10), square=square)
    va.set_title(f'square={square}', ax=ax)

plt.show()

(Source code, svg)

../../../_images/plot_set_limits_square.svg