global legend in matlab in matlab

To create a global legend in MATLAB, you can follow these steps:

  1. Set the legend HandleVisibility property to 'off' for each plot you want to include in the global legend. This will prevent MATLAB from automatically creating new legends for each plot.

  2. Create a new figure and add all the plots you want to include in the legend.

  3. Create a new legend object using the legend function.

  4. Set the String property of the legend object to a cell array of the legend strings for each plot.

  5. Set the Location property of the legend object to 'northoutside' or 'southoutside' to place the legend above or below the plots.

Here's an example of how to create a global legend for multiple plots:

main.m
% create some data
x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);
y3 = tan(x);

% create plots with hidden legends
plot(x, y1, 'DisplayName', 'Sine', 'HandleVisibility', 'off');
hold on;
plot(x, y2, 'DisplayName', 'Cosine', 'HandleVisibility', 'off');
plot(x, y3, 'DisplayName', 'Tangent', 'HandleVisibility', 'off');

% create global legend
lgd = legend('String', {'Sine', 'Cosine', 'Tangent'}, ...
             'Orientation', 'horizontal', 'Location', 'northoutside');
466 chars
16 lines

In this example, we create three plots with hidden legends using the HandleVisibility property. Then we create the global legend using the legend function and set the String property to the legend strings for each plot. Finally, we set the Location property to 'northoutside' to place the legend above the plots.

related categories

gistlibby LogSnag