Skip to content

MATLAB - Add Legend to Axes

MATLAB - Creating Informative Legends for Plots

Section titled “MATLAB - Creating Informative Legends for Plots”

A legend is a crucial component of any scientific or data-driven plot. It acts as a key, explaining what each line style, marker, or color represents in your visualization. A plot without a legend can be ambiguous or misleading. MATLAB provides the flexible legend function to create clear and descriptive legends.

The modern and most robust method for creating legends is to assign a DisplayName to each plot object as you create it. This decouples the plotting code from the legend creation, leading to cleaner and more maintainable code.

% Modern Recommended Method
plot(x1, y1, 'DisplayName', 'Data Series 1')
hold on
plot(x2, y2, 'DisplayName', 'Data Series 2')
hold off
legend
% Legacy / Manual Method
legend('Label 1', 'Label 2', ..., 'Label N')
% Advanced Customization
legend(..., 'Name', Value) % e.g., 'Location', 'northwest'
  • plot(..., 'DisplayName', name): This name-value pair within your plotting function (like plot, scatter, bar, etc.) assigns a label to that specific graphical object. This is the preferred best practice.
  • legend: When called with no arguments, legend automatically finds all plot objects that have a DisplayName property set and creates a legend from them. It intelligently ignores plots without a DisplayName.
  • legend('Label1', 'Label2', ...): This manually assigns labels to the plots in the order they were created. This can be brittle; if you change the plotting order, you must also change the legend order.
  • legend(..., 'Name', Value): Customizes the legend’s properties. The most common is 'Location' to control its position, but you can also change font size, orientation, and more.

Let’s plot sin(x) and cos(x) and use the DisplayName property to create a robust legend.

% 1. Create data
x = linspace(0, 2*pi, 100);
% 2. Create a figure and axes
figure;
ax = gca; % Get current axes handle
% 3. Plot the data, assigning DisplayName to each
plot(ax, x, sin(x), 'b-', 'LineWidth', 2, 'DisplayName', 'sin(x)');
hold on; % Keep the current plot active
plot(ax, x, cos(x), 'r--', 'LineWidth', 2, 'DisplayName', 'cos(x)');
hold off; % Release the plot
% 4. Add titles and labels for context
title(ax, 'Sine and Cosine Functions');
xlabel(ax, 'Angle [rad]');
ylabel(ax, 'Value');
grid on;
% 5. Create the legend automatically
legend;

Benefit: If you decide to add another plot, say tan(x), you just add another plot command with its own DisplayName. The legend command doesn’t need to change at all.

Example 2: Customizing Legend Location and Appearance

Section titled “Example 2: Customizing Legend Location and Appearance”

Sometimes the default legend location covers up important data. You can easily move it.

x = linspace(0, 10, 100);
y1 = exp(-0.2*x) .* sin(x);
y2 = exp(-0.1*x) .* cos(x);
figure;
plot(x, y1, 'DisplayName', 'Damped Sine');
hold on;
plot(x, y2, 'DisplayName', 'Damped Cosine');
hold off;
title('Damped Oscillations');
xlabel('Time [s]');
ylabel('Amplitude');
grid on;
% Create the legend and specify properties
lgd = legend('Location', 'northeast', 'FontSize', 12);
title(lgd, 'Signals'); % Add a title to the legend itself!

Pro Tip: Common 'Location' values include 'best', 'northwest', 'southwest', 'northeast', 'southeast', and 'center'. Using 'best' lets MATLAB try to find the location with the least data overlap.

Example 3: Creating a Legend for a Subset of Plots

Section titled “Example 3: Creating a Legend for a Subset of Plots”

What if you have helper plots (like a trend line) that you don’t want to include in the legend? The DisplayName method handles this automatically. Alternatively, you can manually specify which plots to include.

x = linspace(0, pi, 50);
y1 = cos(x);
p1 = plot(x, y1, 'DisplayName', 'cos(x)'); % Plot with DisplayName
hold on
y2 = 0.5*cos(2*x);
plot(x, y2); % Plot WITHOUT DisplayName
y3 = 0.25*cos(3*x);
p3 = plot(x, y3, 'DisplayName', '0.25*cos(3x)'); % Plot with DisplayName
hold off
title('Including only relevant data in legend');
% Method 1: Automatic (Recommended)
% Simply calling legend will only include p1 and p3
legend('Location', 'southwest');
% --- OR ---
% Method 2: Manual Control (if you need to override)
% legend([p1, p3]); % This achieves the same result by passing handles

In this example, the second plot of 0.5*cos(2*x) is treated as a visual aid and is correctly excluded from the legend because it lacks a DisplayName.

  • Warning: Ignoring extra legend entries: This happens if you use the manual method legend('A', 'B', 'C') but only have two plots on your axes. Ensure the number of labels matches the number of plotted series.
  • Legend is Empty: This can happen if you call legend when no plots have a DisplayName set. Double-check that you’ve added the 'DisplayName' property to your plotting commands.
  • Programmatic Control: For highly dynamic plots, you can programmatically turn off an item’s inclusion in the legend by setting its HandleVisibility property: p.HandleVisibility = 'off';. This is an advanced technique for complex GUIs or apps.