0
0
MatlabHow-ToBeginner ยท 3 min read

How to Set Axis Limits in MATLAB: Simple Guide

In MATLAB, you can set axis limits using the axis function with a vector of limits or use xlim, ylim, and zlim to set limits for each axis individually. For example, axis([xmin xmax ymin ymax]) sets the x and y limits at once.
๐Ÿ“

Syntax

The main ways to set axis limits in MATLAB are:

  • axis([xmin xmax ymin ymax]): Sets limits for x and y axes together.
  • xlim([xmin xmax]): Sets limits for the x-axis only.
  • ylim([ymin ymax]): Sets limits for the y-axis only.
  • zlim([zmin zmax]): Sets limits for the z-axis only (3D plots).

Each limit is a two-element vector specifying the minimum and maximum values shown on that axis.

matlab
axis([xmin xmax ymin ymax])
xlim([xmin xmax])
ylim([ymin ymax])
zlim([zmin zmax])
๐Ÿ’ป

Example

This example shows how to plot a simple sine wave and then set the x-axis limits from 0 to 2*pi and y-axis limits from -1 to 1 using xlim and ylim.

matlab
x = linspace(0, 4*pi, 100);
y = sin(x);
plot(x, y)
xlim([0 2*pi])
ylim([-1 1])
title('Sine Wave with Custom Axis Limits')
xlabel('x')
ylabel('sin(x)')
Output
A plot window showing a sine wave from 0 to 2*pi on the x-axis and -1 to 1 on the y-axis with labeled axes and title.
โš ๏ธ

Common Pitfalls

Common mistakes when setting axis limits include:

  • Using axis with incorrect number of elements (must be 4 for 2D or 6 for 3D).
  • Setting limits that do not include the data range, causing data to be clipped or invisible.
  • Forgetting to call hold on when plotting multiple graphs before setting limits.
  • Using axis tight or axis auto unintentionally overriding manual limits.
matlab
plot(1:10, (1:10).^2)
axis([0 5 0 10]) % Wrong: y limits clip data
% Correct way:
axis([0 10 0 100])
Output
The first plot clips y values above 10, hiding data points; the corrected axis shows all data points.
๐Ÿ“Š

Quick Reference

FunctionPurposeExample Usage
axisSet limits for all axes at onceaxis([xmin xmax ymin ymax])
xlimSet limits for x-axis onlyxlim([xmin xmax])
ylimSet limits for y-axis onlyylim([ymin ymax])
zlimSet limits for z-axis only (3D)zlim([zmin zmax])
โœ…

Key Takeaways

Use axis([xmin xmax ymin ymax]) to set both x and y limits together.
Use xlim, ylim, and zlim to set limits for individual axes.
Make sure axis limits include your data range to avoid clipping.
Avoid conflicting commands like axis auto after setting manual limits.
Always check the number of elements in the vector passed to axis.