Add Legend to Axes in MATLAB
MATLAB provides the legend() function to add legends to a set of axes, which makes legend-making easy and efficient. In this article, we shall see how to add legends to single and multiple cartesian axes in MATLAB with various examples.
Syntax:
plot(…)
legend (‘label1’, ‘label2’, …, ‘label_N’)
Now, the labels could be either string, string vectors, or a cell array.
Adding legend to a simple sine and cosine function plot.
Example 1:
Matlab
% MATLAB code for adding legend to a % simple sine and cosine function plot % Defining xrange rng = linspace(-pi,pi,1000); % Plotting sine plot(rng, sin(rng)) % Holding the earlier plot for simultaneous plotting hold on % Plotting cosine plot(rng,cos(rng)) % Adding legend, with same order as of plotting legend( 'Sine' , 'Cosine' ) |
Output:
Adding legend with cell arrays.
Example 2:
Matlab
% MATLAB code for range rng = linspace(-pi,pi,1000); % Plotting sin^2 plot(rng, sin(rng).^2) hold on % Plotting cos^2 plot(rng,cos(rng).^2) % Creating an array of character vectors lgd = { 'sine' , 'cosine' }; % Converting the array into cell array lgd=cell(lgd); % Adding legend legend(lgd) |
Output:
Now, let us add different legends to multiple axes in the same figure.
Example 3:
Matlab
% MATLAB code to add different legends to % multiple axes in the same figure. rng = linspace(-pi,pi,1000); % Defining two axes ax1 = axes( 'Position' ,[0.05 0.05 0.5 0.5]); ax2 = axes( 'Position' ,[0.6 0.6 0.35 0.35]); % Plotting in each axes plot(ax1, rng, sin(rng).^2) % Plotting legend for axes 1 legend(ax1, 'Sine' ) plot(ax2,cos(rng).^2) % Plotting legend for axes 1 legend(ax2, 'Cosine' ) |
Output:
For changing the location of axes in the graph, we can use the ‘Location’ parameter and specify the location as ‘northeast’, ‘south’ etc. Let us see an example, where we move the legend from northeast to north.
Example 4:
Matlab
% MATLAB code for changing the % location of axes in the graph rng = linspace(-pi,pi,1000); % Plotting curves plot(rng, sin(rng)) hold on plot(rng,cos(rng)) hold off % Adding legend lgd = { 'sine' , 'cosine' }; lgd=cell(lgd); legend(lgd, 'Location' , 'north' ) |
Output: