How to Add Legend in MATLAB: Simple Guide
In MATLAB, you add a legend to a plot using the
legend function by passing labels as strings for each plotted data series. For example, legend('Data1', 'Data2') adds a legend identifying each line or marker in the plot.Syntax
The basic syntax to add a legend in MATLAB is:
legend('label1', 'label2', ...): Adds a legend with specified labels for each plotted data series.legend('show'): Displays the legend if it was previously hidden.legend('off'): Hides the legend.
You can also customize the legend location and appearance using additional name-value pair arguments.
matlab
legend('label1', 'label2', ...) legend('show') legend('off')
Example
This example shows how to plot two lines and add a legend to identify them clearly.
matlab
x = 1:10; y1 = x; y2 = x.^2; plot(x, y1, '-o', x, y2, '-*') legend('Linear', 'Quadratic')
Output
A plot window opens showing two lines: one with circle markers labeled 'Linear' and one with star markers labeled 'Quadratic'. A legend box appears identifying each line accordingly.
Common Pitfalls
Common mistakes when adding legends in MATLAB include:
- Not matching the number of legend labels to the number of plotted data series, which causes errors or incorrect legends.
- Calling
legendbefore plotting data, resulting in an empty or missing legend. - Overlapping legend with plot data if the default location is not suitable.
Always ensure your legend labels correspond exactly to the plotted lines or markers.
matlab
plot(1:5) legend('Only one label') % Correct plot(1:5, 1:5, 1:5, (1:5).^2) legend('One label') % Incorrect: fewer labels than lines % Correct way: plot(1:5, 1:5, 1:5, (1:5).^2) legend('Line 1', 'Line 2', 'Line 3')
Quick Reference
| Command | Description |
|---|---|
| legend('label1', 'label2', ...) | Add legend with specified labels |
| legend('show') | Show the legend if hidden |
| legend('off') | Hide the legend |
| legend('Location', 'best') | Place legend at best location automatically |
| legend('Location', 'northwest') | Place legend at top-left corner |
Key Takeaways
Use
legend with labels matching the number of plotted data series.Call
legend after plotting your data to ensure it appears correctly.Customize legend location with the 'Location' option to avoid overlap.
Use
legend('show') and legend('off') to toggle legend visibility.Always check that legend labels clearly describe each plot element for clarity.