Skip to main content
v2026.11,858 entries · CC-BY 4.0

xlim MATLAB: Set & Manage X-Axis Limits

Master xlim in MATLAB to set and query x-axis limits, configure datetime scales, enable semiautomatic bounds, and synchronize multi-panel research figures.

Written and maintained by CASRAI Editorial Board

Last updated

In MATLAB, xlim is the built-in graphics function used to set or query the horizontal coordinate limits of 2D and 3D axes. It allows researchers to define the visible viewport range, focus on specific experimental intervals, synchronize axes across subplots, and configure datetime rulers without altering underlying numerical arrays.

What it is used for in research

Data visualization in academic research requires precise control over coordinate axes. By default, MATLAB automatically scales axes to envelope all plotted data points. While convenient during preliminary data exploration, automatic scaling frequently causes presentation inconsistencies across comparative experiments, obscures subtle baseline variations, or leaves excess margins around critical signal features.

Researchers utilize xlim across several core workflows:

  • Standardizing Comparative Subplots: When presenting multi-panel plots across experimental trials or treatment cohorts, ensuring uniform horizontal spans allows readers to accurately evaluate effect timing and peak alignment without cognitive distortion.
  • Isolating Regions of Interest: In electrophysiology, spectroscopy, and time-series econometrics, researchers frequently zoom into specific epochs (such as stimulus onset windows or frequency bands) by setting explicit lower and upper boundaries.
  • Managing Datetime and Time-Series Series: Modern academic datasets often index measurements by calendar timestamps or elapsed runtimes. The xlim command directly accepts MATLAB datetime and duration vectors, maintaining calibrated temporal axes.
  • Preserving Zero Baselines with Semiautomatic Limits: Researchers can pin a lower baseline to zero while allowing the upper bound to scale dynamically as incoming observations expand.

For foundational visualization concepts, consult our guide on MATLAB graphing and techniques for managing MATLAB figure windows.

Install or access (official source only)

The xlim function is an integral component of core MATLAB handle graphics and requires no external toolboxes. Official access pathways include:

  • MATLAB Desktop: Licensed and installed through the official MathWorks portal via university campus agreements, research institute site licenses, or individual practitioner licenses. Installations are managed through the MathWorks installer for Windows, macOS, and Linux.
  • MATLAB Online: Web-based computational access hosted on MathWorks cloud infrastructure (accessible at matlab.mathworks.com) through modern web browsers.
  • GNU Octave (Compatible Environment): An official open-source software alternative providing direct syntax compatibility for xlim, accessible via the official GNU project portal and standard distribution package repositories.

For verifying function signatures and built-in help in your local environment, use the MATLAB documentation system from the command prompt.

Step-by-step task

The following numbered steps demonstrate standard workflows for configuring x-axis limits in MATLAB scripts, Live Scripts, and command-line sessions. For script structuring best practices, see our tutorial on MATLAB script automation.

Step 1: Inspect Default Automatic Limits

When you generate a plot, MATLAB sets the axes property XLimMode to 'auto'. To query the boundaries calculated by MATLAB, call xlim with no arguments:

x = linspace(0, 10, 500);
y = sin(x);
plot(x, y);

% Query current x-axis boundaries
current_limits = xlim;
disp(current_limits);

The function returns a 1×2 row vector [xmin xmax] containing the active bounds.

Step 2: Apply Fixed Numerical Bounds

To specify explicit coordinate bounds, pass a two-element vector [xmin xmax] where xmax > xmin:

% Constrain the view to the interval [2, 8]
xlim([2, 8]);

Applying numeric limits automatically updates the underlying axes property XLimMode from 'auto' to 'manual', ensuring that subsequent plotting calls with hold on do not expand the viewport.

Step 3: Configure Semiautomatic Bounds

When you want to anchor one boundary while allowing MATLAB to dynamically calculate the opposing boundary based on data extremes, use -inf or inf:

% Pin the lower limit at 0 and let MATLAB determine the upper limit
xlim([0, inf]);

% Fix upper limit at 5 and let MATLAB determine the lower limit
xlim([-inf, 5]);

Step 4: Target Specific Axes Handles in Multi-Panel Layouts

In multi-panel scientific figures created with tiledlayout or subplot, calling xlim(...) modifies only the current active axes (gca). To target a specific panel unambiguously, pass its axes handle as the first argument:

fig = figure;
t = tiledlayout(2, 1);

% Panel 1
ax1 = nexttile;
plot(ax1, x, sin(x));
xlim(ax1, [0, 5]);

% Panel 2
ax2 = nexttile;
plot(ax2, x, cos(x));
xlim(ax2, [0, 10]);

To synchronize horizontal scrolling and zooming across both panels, link their x-axes:

linkaxes([ax1, ax2], 'x');

Step 5: Configure Datetime and Duration Scales

For longitudinal studies where the horizontal axis represents calendar time or duration intervals, provide bounds matching the ruler data type:

dates = datetime(2026, 1, 1) + caldays(0:90);
values = cumsum(randn(1, 91));
plot(dates, values);

% Set datetime limits
xlim([datetime(2026, 1, 15), datetime(2026, 2, 28)]);

Step 6: Restore Automatic Scaling

To revert manual boundaries back to dynamic auto-scaling, set the limit mode to 'auto':

xlim('auto');

% Verify current mode
current_mode = xlim('mode');
disp(current_mode); % Returns 'auto'

Output and how to read it

The xlim command produces two forms of output depending on whether it is invoked as a setter or a getter:

  • Query Output (Getter): Invoking lims = xlim returns a 1×2 row vector of class double (or matching ruler type such as datetime or duration). The first element lims(1) represents the minimum visible x-axis value (left edge), and lims(2) represents the maximum visible value (right edge). Calling m = xlim('mode') returns a character vector: either 'auto' or 'manual'.
  • Visual Viewport Adjustment: Invoking xlim([xmin xmax]) alters the rendered coordinate window and triggers automatic regeneration of tick mark locations (XTick) and labels (XTickLabel).

Crucially, setting xlim changes the camera view frustum; it does not truncate or discard observations from the underlying graphics series or data arrays. Numerical analyses operating on the raw data matrices remain unaffected by visual zoom operations.

Troubleshooting

The following table addresses common technical issues encountered when adjusting x-axis limits in MATLAB:

Symptom or Error Root Cause Resolution
Error: Lower limit must be less than upper limit Attempting to invert the horizontal axis by supplying [xmax xmin] where the first value exceeds the second. Maintain xmin < xmax in xlim([xmin xmax]). To reverse the visual axis direction, execute set(gca, 'XDir', 'reverse').
Conversion to double from datetime is not possible Passing numeric values (e.g. [0 50]) to an axes ruler configured for datetime or duration objects. Provide boundary values using the matching type: xlim([datetime(2026,1,1) datetime(2026,6,1)]).
Limits reset unexpectedly after calling plot Default behavior of high-level plotting functions when hold on is not active resets XLimMode to 'auto'. Issue hold on before subsequent plotting calls, or invoke xlim(...) after all data series have been rendered.
Wrong subplot modified Calling xlim(...) without an explicit axes handle targets whatever axes MATLAB designates as gca. Store the axes handle during creation (e.g., ax = nexttile; or ax = subplot(2,1,1);) and pass it explicitly: xlim(ax, [xmin xmax]).
Plotted curve disappears completely Supplied boundaries fall outside the coordinate domain of the dataset. Call xlim('auto') to inspect data span, or calculate bounds dynamically: xlim([min(x) max(x)]).

Free alternatives (table)

Researchers working in open-source computational environments can manage horizontal plot limits using the following verified alternatives:

Environment / Library Axis Limit Syntax Semiautomatic Limits Behavioral Mechanism License
GNU Octave xlim([xmin xmax]) Yes (-Inf, Inf) Direct drop-in replacement; modifies axes XLim and XLimMode handle properties. GPLv3
Python Matplotlib ax.set_xlim(xmin, xmax) or plt.xlim(xmin, xmax) Yes (pass None for either limit) Adjusts view margins without modifying underlying data arrays. PSF / BSD-compatible
R (ggplot2) coord_cartesian(xlim = c(xmin, xmax)) Yes (c(NA, xmax) or c(xmin, NA)) True visual zooming; preserves data points outside limits for stat calculations. GPL-2 | GPL-3
R (Base Graphics) plot(x, y, xlim = c(xmin, xmax)) No (requires explicit numeric bounds) Sets plot boundaries at plot initialization. GPL-2 | GPL-3
Julia (Plots.jl) xlims!((xmin, xmax)) No (requires explicit numeric tuple) Modifies current plot recipe attributes. MIT

FAQ

How do you reverse the x-axis direction in MATLAB while using xlim?

To display data with decreasing values from left to right, do not invert the order in xlim. MATLAB requires xmin < xmax in xlim([xmin xmax]); passing inverted values triggers an error. Instead, keep standard bounds and set the axes direction property: set(gca, 'XDir', 'reverse').

How can you synchronize x-axis limits across multiple subplots?

Use the linkaxes command. Store the axes handles in an array and pass the dimension to synchronize: linkaxes([ax1, ax2, ax3], 'x'). Any subsequent zoom, pan, or xlim adjustment made to one panel updates all linked panels simultaneously.

What is the difference between xlim(‘auto’) and xlim(‘manual’)?

In 'auto' mode, MATLAB recalculates the limits whenever new series are added or figure windows are resized. In 'manual' mode, MATLAB locks the axis bounds to their current values, preventing incoming data from changing the horizontal scale.

How do you set one-sided axis limits in MATLAB?

Pass -inf or inf inside the two-element limit vector. For example, xlim([0, inf]) anchors the minimum boundary at zero while allowing MATLAB to automatically calculate the maximum based on data extremes.

Can you use xlim with datetime or duration data?

Yes. When plotting time-series where the x-axis is governed by datetime or duration values, provide a vector of two matching objects: xlim([datetime(2026,1,1), datetime(2026,6,30)]). Supplying numeric values to a datetime axis causes a type mismatch error.

Sources (official docs)

Follow CASRAI

Research-administration guidance, standards updates and independent tool reviews.

Ask CASRAI · free to try

Ask about xlim MATLAB: Set & Manage X-Axis Limits

Ask your first 2 questions free below. Subscribers get 150 a day for $29 a month.

An AI assistant specialized in research administration. It cites the sources behind every answer, labels web answers and says when it can't answer.

Answers draw on CASRAI's guides and dictionary plus the federal and funder documents we index: Federal Register, Grants.gov, Regulations.gov and UKRI.

Works on this site and inside Claude, Cursor and the AI tools you already use.

Everything CASRAI publishes — this page, the dictionary, the guides and the news — stays free to read, with no account and no card.

Referenced across the research world

University of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logoUniversity of Cambridge logoColumbia University logoCrossref logoUniversity of Edinburgh logoHarvard University logoUniversity of Oxford logoPrinceton University logoStanford School of Medicine logoUniversity College London logoORCID logo
  • University of Cambridge logo
  • Columbia University logo
  • Crossref logo
  • University of Edinburgh logo
  • Harvard University logo
  • University of Oxford logo
  • Princeton University logo
  • Stanford School of Medicine logo
  • University College London logo
  • ORCID logo

View CASRAI adoption →