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
axiswith 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 onwhen plotting multiple graphs before setting limits. - Using
axis tightoraxis autounintentionally 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
| Function | Purpose | Example Usage |
|---|---|---|
| axis | Set limits for all axes at once | axis([xmin xmax ymin ymax]) |
| xlim | Set limits for x-axis only | xlim([xmin xmax]) |
| ylim | Set limits for y-axis only | ylim([ymin ymax]) |
| zlim | Set 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.