Filter löschen
Filter löschen

Multiple plots with same Legend

531 Ansichten (letzte 30 Tage)
Omar
Omar am 9 Mär. 2018
Beantwortet: Ridouane OULHIQ am 13 Aug. 2023
Hi colleagues, Is there a way to group different subplots with one legend. for example, I have two subplots as [subplot(1,2,1 and subplot(1,2,2)], is it possible to use the same legend for both?
Thanks in advance,

Akzeptierte Antwort

Prajith Chilummula
Prajith Chilummula am 12 Mär. 2018
The issue here is that each legend needs to be associated with an axis. There is no built-in way to create an "overall legend". But it is perfectly fine to use a legend associated with a subplot as an overall legend. You will have to play with the legend's position to achieve the desired look.
The easiest way to do it is manually, by dragging the legend inside the figure.
It is a bit more involved programmatically. Here is an example:
subplot(2, 2, 1)
A = rand(10, 3);
plot(A, '-o')
hold on
b = rand(10, 1);
plot(b, '-k', 'LineWidth', 3)
subplot(2, 2, 2)
A = rand(10, 3);
plot(A, '-o')
hold on
b = rand(10, 1);
plot(b, '-k', 'LineWidth', 3)
subplot(2, 2, 3)
A = rand(10, 3);
plot(A, '-o')
hold on
b = rand(10, 1);
plot(b, '-k', 'LineWidth', 3)
subplot(2, 2, 4)
A = rand(10, 3);
plot(A, '-o', 'DisplayName', 'Data')
hold on
b = rand(10, 1);
plot(b, '-k', 'LineWidth', 4, 'DisplayName', 'Trend')
% add a bit space to the figure
fig = gcf;
fig.Position(3) = fig.Position(3) + 250;
% add legend
Lgnd = legend('show');
Lgnd.Position(1) = 0.01;
Lgnd.Position(2) = 0.4;

Weitere Antworten (2)

Adam Danz
Adam Danz am 29 Sep. 2020
Bearbeitet: Adam Danz am 29 Sep. 2020
Update
The graphics handles vector h in legend(h) can contain objects from any axes (created by axes(), subplot(), or tiledlayout()) from within a figure. As Prajith mentioned, the legend must be a child of a single axes but it can then be repositioned to anywhere within the figure. Starting in the r2020b release, legend positions can be changed with TiledLayout as well.
Examples:

Ridouane OULHIQ
Ridouane OULHIQ am 13 Aug. 2023
You can generate a legend with the option :'Location', 'northoutside' to be outside one of the subplots, then change its position to where you want it to be.
See example below:
t = 1:100;
subplot(1,2,1);
plot(t);
hold on
plot(t+10);
subplot(1,2,2);
plot(t);
hold on
plot(t+10);
leg = legend('t1','t2', 'Location','northoutside','orientation','horizontal');
leg.Position(1) = 0.4;
leg.Position(2) = 0.95;

Kategorien

Mehr zu 2-D and 3-D Plots finden Sie in Help Center und File Exchange

Community Treasure Hunt

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

Start Hunting!

Translated by