Add Legend to Axes in MATLAB
Last Updated :
03 Nov, 2022
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
rng = linspace(-pi,pi,1000);
plot(rng, sin(rng))
hold on
plot(rng,cos(rng))
legend( 'Sine' , 'Cosine' )
|
Output:
Adding legend with cell arrays.
Example 2:
Matlab
rng = linspace(-pi,pi,1000);
plot(rng, sin(rng).^2)
hold on
plot(rng,cos(rng).^2)
lgd = { 'sine' , 'cosine' };
lgd=cell(lgd);
legend(lgd)
|
Output:
Now, let us add different legends to multiple axes in the same figure.
Example 3:
Matlab
rng = linspace(-pi,pi,1000);
ax1 = axes( 'Position' ,[0.05 0.05 0.5 0.5]);
ax2 = axes( 'Position' ,[0.6 0.6 0.35 0.35]);
plot(ax1, rng, sin(rng).^2)
legend(ax1, 'Sine' )
plot(ax2,cos(rng).^2)
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
rng = linspace(-pi,pi,1000);
plot(rng, sin(rng))
hold on
plot(rng,cos(rng))
hold off
lgd = { 'sine' , 'cosine' };
lgd=cell(lgd);
legend(lgd, 'Location' , 'north' )
|
Output:
Share your thoughts in the comments
Please Login to comment...