How to add a second legend-box to a figure without new plots?

1.225 views (last 30 days)
Hey everyone, I already looked into the answers of the MATLAB-Community that were given to questions very similar to mine (https://de.mathworks.com/matlabcentral/answers/367161-2-legends-in-1-plot; https://de.mathworks.com/matlabcentral/answers/365006-how-to-create-2-legends-in-one-figure)
I tried these solutions, but they didn't work for me. That's why I am asking for help here.
To describe my problem, here are the facts:
  • I want to plot several functions, some are shown as solid lines and some as dotted lines
  • I added a legend to name these lines by color
  • Now I want to explain what the normal, solid lines are standing for and what the dotted-lines are standing for
  • I want to do this by adding a second legend (in an own "legend-window") to the figure
As far as I know, you can only have one legend-window for one set of axes in MATLAB, so the idea is:
  • add a second (exatly equal) set of axes to the figure
  • make this axes invisible, so you don't see it later in the plot
  • add two "helping - lines", one solid and one dotted
  • make these helping - lines also invisible
  • add a second legend to describe the helping - lines
As you can see in the following code, I made an example of how I tried to find a solution for my problem with simple functions.
It does't work good, because the second set of axes ('secondaxes') is not invisible and the second legend (the one with 'Model' and 'Catalogue' in it) is not black, but grey, because I had to make the helping lines H1 and H2 invisible...
clear all
% First Line to plot:
t = 0:0.5:5;
f = (2*sin(2*60*t));
% "Helping Lines", for example k and r:
p = 0:0.5:5;
k = 2*p + 3;
o = 0:0.5:5;
r = 2*o +3.2;
%%%%%%%%% First plot (L1) and the axes for that plot (firstax) %%%%%%%%
f1 = figure;
firstax = axes (f1, 'FontSize', 16);
hold on
xlim ([0 100]);
xlabel('Current [A]');
ylabel('Voltage [V]');
L1 = plot (f, '-', 'LineWidth', 2, 'Color', [0 84 159]/255, 'Parent', firstax);
hold off
set(firstax, 'Box', 'off')
legend(firstax, L1, '4 A', 'Location', 'southeast');
%%%%%% axes for the second plot (secondaxes) and the two helping Lines H1 and H2 %%%%%%%%
hold on
secondax = copyobj(firstax, gcf);
delete( get(secondax, 'Children'))
H1 = plot(k, '-', 'LineWidth', 2, 'Color', [0 0 0]/255, 'Parent', secondax, 'Visible', 'off');
H2 = plot(r, '--', 'LineWidth', 2, 'Color', [0 0 0]/255, 'Parent', secondax, 'Visible', 'off');
set(secondax, 'Color', 'none', 'XTick', [], 'YAxisLocation', 'right', 'Box', 'Off')
legend (secondax, [H1 H2], 'Model', 'Catalogue', 'Location', 'northeast');
hold off

Accepted Answer

Cris LaPierre
Cris LaPierre on 21 Nov 2018
Do you want to have two different scales on the y axes?
Modifying the placement of holds and labels seemed to fix seeing the double axes. I assume at some point you will be adding real data for H1 and H2 that won't be hidden, so that legend will appear the same. The background color can be changed by adding a Color name-value pair to the legend command.
...
%%%%%%%%% First plot (L1) and the axes for that plot (firstax) %%%%%%%%
f1 = figure;
firstax = axes (f1, 'FontSize', 16);
L1 = plot (f, '-', 'LineWidth', 2, 'Color', [0 84 159]/255, 'Parent', firstax);
set(firstax, 'Box', 'off','XLim',[0 100]);
legend(firstax, L1, {'4 A'}, 'Location', 'southeast');
%%%%%% axes for the second plot (secondaxes) and the two helping Lines H1 and H2 %%%%%%%%
hold on
secondax = copyobj(firstax, gcf);
delete( get(secondax, 'Children'))
H1 = plot(k, '-', 'LineWidth', 2, 'Color', [0 0 0]/255, 'Parent', secondax, 'Visible', 'off');
H2 = plot(r, '--', 'LineWidth', 2, 'Color', [0 0 0]/255, 'Parent', secondax, 'Visible', 'off');
set(secondax, 'Color', 'none', 'XTick', [], 'YAxisLocation', 'right', 'Box', 'Off')
legend ([H1 H2], {'Model', 'Catalogue'}, 'Location', 'northeast');
hold off
xlabel('Current [A]');
ylabel('Voltage [V]');
2legends.png
  3 Comments
Davide Zamblera
Davide Zamblera on 24 Nov 2022
You can change the legend color by adding the corresponding attribute:
legend ([H1 H2], 'Model', 'Catalogue', 'Location', 'northeast', 'Color',[1 1 1]);

Sign in to comment.

More Answers (2)

Hamdullah Livaoglu
Hamdullah Livaoglu on 9 Jul 2019
Another approach is here; (R2015b)
characterizing multi properties for its legends in the same figure ; (legendTitle function is derived from https://nl.mathworks.com/matlabcentral/fileexchange/48331-add-a-title-to-a-legend)
hold on
col = rand(length(hv),3);
for j = 1 : length(hv)
p(j)=plot(sPeriod,hv{j},'Color', col(j,:),'LineWidth',1.2);
p1(j)=plot(sPeriod,hv{j},'Color', col(j,:),'LineWidth',1.2);
end
xlabel('Predominant Periods (s)','FontWeight','bold');
ylabel('Response Spectral Ratios (RHV)','FontWeight','bold');
set(gca, 'XScale', 'log');
set(gca, 'XLim', [0.05 2]);
set(gca, 'XTick', [0.05 0.1 0.2 0.4 0.6 0.8 1.5 2]);
hold off
agsdgsgsdg.jpg
leg1=legend(p,num2str(round(R(ind)')),'Location','NorthEast');set(leg1,'FontSize',9);
ah1=axes('position',get(gca,'position'),'visible','off');
leg2=legend(ah1,p1,magnitude{ind},'Location','NorthWest');set(leg2,'FontSize',9);
legendTitle (leg1, 'R (km)' );
legendTitle (leg2, 'Magnitude' );
  2 Comments
Sedevizo Kielienyu
Sedevizo Kielienyu on 17 Jul 2020
Thank you so much! I have been looking everywhere to display two legends. Your method is the only one that worked for me.

Sign in to comment.


Anna
Anna on 4 Nov 2020
Edited: Anna on 4 Nov 2020
Here's a minimal working example with more than one line (works on R2017b):
%% define data
% data
x = 0:0.5:5;
y1 = (2*sin(2*60*x));
y2 = (2*cos(2*60*x));
y3 = (2*sin(60*x));
y4 = (2*cos(60*x));
% helper data (as many as different line styles are required)
h1 = 2*x + 3;
h2 = 2*x +3.2;
%% create plot
f1 = figure();
Ax(1) = axes(f1);
xlabel('x data');
ylabel('y data');
hold on
Y1 = plot(x,y1, '-', 'LineWidth', 2, 'Color', [0 0 1], 'Parent', Ax(1));
Y2 = plot(x,y2, '-', 'LineWidth', 2, 'Color', [1 0 0], 'Parent', Ax(1));
Y3 = plot(x,y3, '--', 'LineWidth', 2, 'Color', [0 0 1], 'Parent', Ax(1));
Y4 = plot(x,y4, '--', 'LineWidth', 2, 'Color', [1 0 0], 'Parent', Ax(1));
% do NOT hold off here!
set(Ax(1), 'Box','off')
% add colour legend
lgd1 = legend(Ax(1), [Y1 Y2],'blue','red', 'Location', 'southeast'); % only select first two data lines, as there's only two different colours
title(lgd1,'Colours') % add legend title
% copy axes
Ax(2) = copyobj(Ax(1),gcf);
delete(get(Ax(2), 'Children') )
% plot helper data, but invisible
hold on
H1 = plot(x,h1, '-', 'LineWidth', 2, 'Color', [0 0 0], 'Parent', Ax(2),'Visible', 'off');
H2 = plot(x,h2, '--', 'LineWidth', 2, 'Color', [0 0 0], 'Parent', Ax(2),'Visible', 'off');
hold off
% make second axes invisible
set(Ax(2), 'Color', 'none', 'XTick', [], 'YAxisLocation', 'right', 'Box', 'Off', 'Visible', 'off')
% add linestyle legend
lgd2 = legend([H1 H2], 'Linestyle 1', 'Linestyle 2', 'Location', 'northeast');
title(lgd2,'Linestyles') % add legend title
set(lgd2,'color','none')
  1 Comment
Leone Campos
Leone Campos on 17 Nov 2022
Nicely done!
If you want the second legend to be black instead of greyed out, you can plot dummy points and keep them visible:
H1 = plot(NaN,NaN, '-', 'LineWidth', 2, 'Color', [0 0 0], 'Parent', Ax(2));
H2 = plot(NaN,NaN, '--', 'LineWidth', 2, 'Color', [0 0 0], 'Parent', Ax(2));

Sign in to comment.

Community Treasure Hunt

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

Start Hunting!

Translated by