Is there a command in MATLAB for creating one overall legend when I have a figure with subplots?

1,531 ビュー (過去 30 日間)
Is there a command in MATLAB for creating one overall legend when I have a figure with subplots?
I have a figure with subplots and I would like to create one legend that refers to all of my subplots. Is there a way to do this?

採用された回答

MathWorks Support Team
MathWorks Support Team 2022 年 8 月 16 日
編集済み: MathWorks Support Team 2022 年 8 月 17 日
You can create an overall legend by first using 'tiledlayout' to create your subplots. Then, generate the legend and specify what should appear in the legend using a vector of graphics object handles. The position of the legend can be set by its 'Layout' property. Find an example of this workflow below.
figure()
tcl = tiledlayout(2,2);
nexttile(tcl)
line1 = plot(1:10,rand(1,10),'b','DisplayName','Data Axes 1');
title('Axes 1');
nexttile(tcl)
line2 = plot(1:10,rand(1,10),'g','DisplayName','Data Axes 2');
title('Axes 2');
nexttile(tcl)
line3 = plot(1:10,rand(1,10),'r','DisplayName','Data Axes 3');
title('Axes 3');
nexttile(tcl)
line4 = plot(1:10,rand(1,10),'c','DisplayName','Data Axes 4');
title('Axes 4');
% Construct a Legend with the data from the sub-plots
hL = legend([line1,line2,line3,line4]);
% Move the legend to the right side of the figure
hL.Layout.Tile = 'East';
For for information on the 'Layout' property, refer to this page: 
For MATLAB versions prior to MATLAB R2019b or code that uses 'subplot' instead of 'tiledlayout', there is no straight-forward way to create an overall legend. A workaround is to create an extra subplot, or an additional row or column, and use that space for the legend. Here is an example that uses a 2-by-2 grid of subplots with a third column reserved for the legend.
figure()
subplot(2,3,1)
line1 = plot(1:10,rand(1,10),'b','DisplayName','Data Axes 1');
title('Axes 1');
subplot(2,3,2)
line2 = plot(1:10,rand(1,10),'g','DisplayName','Data Axes 2');
title('Axes 2');
subplot(2,3,4)
line3 = plot(1:10,rand(1,10),'r','DisplayName','Data Axes 3');
title('Axes 3');
subplot(2,3,5)
line4 = plot(1:10,rand(1,10),'c','DisplayName','Data Axes 4');
title('Axes 4');
% Create a tile on the right column to get its position
ax = subplot(2,3,3,'Visible','off');
axPos = ax.Position;
delete(ax)
% Construct a Legend with the data from the sub-plots
hL = legend([line1,line2,line3,line4]);
% Move the legend to the position of the extra axes
hL.Position(1:2) = axPos(1:2);
You may use the 'Position' property of the legend to relocate it, for example, to adjust its vertical position.
  4 件のコメント
Eric Sargent
Eric Sargent 2020 年 12 月 9 日
Starting in R2019a, you can use tiledlayout to create an "overall legend" effect. The code below attaches a legend to the second axes but places it outside of the layout.
tiledlayout(2,2, 'TileSpacing', 'compact')
nexttile
line1 = plot(1:10,rand(1,10),'b', 'DisplayName', 'Data Axes 1');
title('Axes 1');
nexttile
line2 = plot(1:10,rand(1,10),'g', 'DisplayName', 'Data Axes 2');
title('Axes 2');
nexttile
line3 = plot(1:10,rand(1,10),'r', 'DisplayName', 'Data Axes 3');
title('Axes 3');
nexttile
line4 = plot(1:10,rand(1,10),'c', 'DisplayName', 'Data Axes 4');
title('Axes 4');
% Create a Legend with the data from multiple axes
lg = legend(nexttile(2), [line1,line2,line3,line4]);
lg.Location = 'northeastoutside';

サインインしてコメントする。

その他の回答 (8 件)

Myrthala Wong
Myrthala Wong 2016 年 9 月 16 日
編集済み: Walter Roberson 2016 年 10 月 1 日
Had the same problem today. I have my subplots in a for loop, so what I did was tell the loop to only place the label in the first plot.
i=1;
for j=1:3;
subplot(...);
plot(...); hold on;
plot(...);
if i==1
AX=legend('plot 1', 'plot 2','location','northeast',orientation,'horizontal');
% places the legend in the top right side of the first graph in my subplot
end
end
Hope somebody else finds it of help.
  3 件のコメント

サインインしてコメントする。


Stephanie Burrows
Stephanie Burrows 2021 年 7 月 9 日
編集済み: Stephanie Burrows 2021 年 7 月 9 日
As noted by previous answers, there is no easy way to do this in MATLAB.
None of the previous answers quite worked for my application, so I'll note my particular workaround below in case it's of use to anybody.
In particular, I needed to add a very large legend outside of the plots. You can see my results below.
%% Set up the data (just enough to need a large legend and to show variety)
t = linspace(0, 1, 11);
x = linspace(0, 1, 100)';
L = [6 2 3 7];
k = [10 20 30 60];
%% Start plotting
% Use an extra two plots spaces in subplot where the legend will go
figind = [1 2 4 5]; % locations where we actually want to plot data
figure(1)
for i=1:length(L)
subplot(2, 3, figind(i))
A = L(i) ./ (1 + exp(-k(i)*t.*x)); % the data to plot
plot(x, A)
xlabel('x')
ylabel('y')
title(sprintf('L = %i, k = %i', L(i), k(i)))
end
subplot (2, 3, [3 6]) % merge remaining subplots and put legend here
plot(x, nan) % plot nans (hack to generate correct legend but plot no data)
legend(sprintfc('t = %0.2f', t), 'Location', 'west');
axis off
The results of the example above are shown below.

Sam
Sam 2014 年 7 月 31 日
If you have empty space in your figure (i.e., not all subplot spaces get used), you can put the legend in an empty space. Let's say you have a figure with 3x4 subplots but only 11 used. You can put the legend in the empty space by doing
subplot(3,4,12)
axis off
before the legend() command.
  3 件のコメント
Wei Ji
Wei Ji 2018 年 11 月 10 日
編集済み: Wei Ji 2018 年 11 月 10 日
This combined with the modification by Matt Hamilton does work perfectly. Thanks!

サインインしてコメントする。


Amin Rajabi
Amin Rajabi 2018 年 11 月 18 日
Unfortunately, like many other basic features, Matlab doesn't support this feature.
I solved it by adding one row at the bottom. It's the easiest way I found out and works well.
For example, consider the case that we have 4 subplots (which are plotted in two rows and two columns) and we want a horizontal common legend for all of them at the bottom. Insted of creating just 4 subplots, we creat 6 subplots (one more row) and then merge the last row, turn the axis off and put the legend there. The code is like this:
for i=1:4
subplot(3,2,,i)
p= plot(x,y) % the plot we want to creat
end
subplot (3,2,[5,6]) % merge two subplots together
axis off
legend([p(1),p(2),p(3),p(4)],{'A','B.','C','D'}, ,'Orientation','horizontal');
(Remember: The legend may be plotted in the middle, buy you can easily drag it and put it in the area which is created.)

Eric Sargent
Eric Sargent 2020 年 12 月 9 日
Starting in R2019a, you can use tiledlayout to create an "overall legend" effect. The code below attaches a legend to the second axes but places it outside of the layout.
tiledlayout(2,2, 'TileSpacing', 'compact')
nexttile
line1 = plot(1:10,rand(1,10),'b', 'DisplayName', 'Data Axes 1');
title('Axes 1');
nexttile
line2 = plot(1:10,rand(1,10),'g', 'DisplayName', 'Data Axes 2');
title('Axes 2');
nexttile
line3 = plot(1:10,rand(1,10),'r', 'DisplayName', 'Data Axes 3');
title('Axes 3');
nexttile
line4 = plot(1:10,rand(1,10),'c', 'DisplayName', 'Data Axes 4');
title('Axes 4');
% Create a Legend with the data from multiple axes
lg = legend(nexttile(2), [line1,line2,line3,line4]);
lg.Location = 'northeastoutside';

Preethi R S
Preethi R S 2021 年 4 月 27 日
There is no straightforward way to have a single legend for all subplots. But it will be possible to turn off legend for specific subplot with the option "Visible".
For example:
subplot(2,1,1)
plot(1:10,rand(1,10),'displayname','first plot')
hold on
plot(1:10,rand(1,10),'displayname','second plot')
legend; % legend is shown for this subplot
subplot(2,1,2)
plot(1:10,rand(1,10),'displayname','first plot')
hold on
plot(1:10,rand(1,10),'displayname','second plot')
h = legend
h.Visible = 'off'; % turn off the legend only for this subplot

Laurent Chauvin
Laurent Chauvin 2018 年 8 月 9 日
Unfortunately, this method does not work with histograms:
% Construct a figure with subplots and data
subplot(2,2,1);
line1 = histogram(rand(1,1000));
title('Axes 1');
subplot(2,2,2);
line2 = histogram(rand(1,1000));
title('Axes 2');
subplot(2,2,3);
line3 = histogram(rand(1,1000));
title('Axes 3');
subplot(2,2,4);
line4 = histogram(rand(1,1000));
title('Axes 4');
% Construct a Legend with the data from the sub-plots
hL = legend([line1,line2,line3,line4],{'Data Axes 1','Data Axes 2','Data Axes 3','Data Axes 4'});
% Programatically move the Legend
newPosition = [0.4 0.4 0.2 0.2];
newUnits = 'normalized';
set(hL,'Position', newPosition,'Units', newUnits);
Does anybody knows how to do that with histograms please?
Thank you.

Joern Adermann
Joern Adermann 2018 年 12 月 28 日
Hello, thank you for the last post. I tried this but it will delete or overwrite my plot so the figure ends up beeing empty.
  1 件のコメント
Amin Rajabi
Amin Rajabi 2018 年 12 月 30 日
Hi Joern,
If you mean my answer, it works well and doesn't have any complicated part. If you could share your code, I might be able to help. Thanks.

サインインしてコメントする。

製品


リリース

R2022a

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by