How to Add xlabel and ylabel in MATLAB Plots
In MATLAB, you add labels to the x-axis and y-axis of a plot using the
xlabel and ylabel functions. Simply call xlabel('Your X Label') and ylabel('Your Y Label') after plotting your data to set the axis labels.Syntax
The basic syntax to add labels to your plot axes in MATLAB is:
xlabel('text'): Adds a label to the x-axis.ylabel('text'): Adds a label to the y-axis.
Replace 'text' with the string you want to display as the label.
matlab
xlabel('X-axis label') ylabel('Y-axis label')
Example
This example shows how to plot a simple line and add labels to both axes for clarity.
matlab
x = 1:10; y = x.^2; plot(x, y) xlabel('Input Value') ylabel('Squared Value')
Output
A plot window opens showing a curve with 'Input Value' labeled on the x-axis and 'Squared Value' labeled on the y-axis.
Common Pitfalls
Common mistakes when adding axis labels include:
- Forgetting to call
xlabelorylabelafter plotting, so labels do not appear. - Using incorrect syntax like missing quotes around the label text.
- Overwriting the plot after labeling without reapplying labels.
Always add labels after the plot command and use quotes around label text.
matlab
plot(1:5, (1:5).^2) xlabel('X-axis') % Corrected: added quotes ylabel('Y-axis') % Correct way: plot(1:5, (1:5).^2) xlabel('X-axis') ylabel('Y-axis')
Quick Reference
Here is a quick summary of how to add axis labels in MATLAB:
| Function | Purpose | Example |
|---|---|---|
| xlabel('text') | Sets label for x-axis | xlabel('Time (s)') |
| ylabel('text') | Sets label for y-axis | ylabel('Amplitude') |
Key Takeaways
Use xlabel('text') and ylabel('text') to add axis labels in MATLAB plots.
Always call these functions after plotting your data to see the labels.
Put the label text inside single quotes to avoid syntax errors.
Check your plot window to confirm labels appear as expected.