Filter löschen
Filter löschen

2 legends in 1 plot

7 Ansichten (letzte 30 Tage)
Steineklopfer
Steineklopfer am 15 Nov. 2017
Bearbeitet: Lee Key am 7 Mär. 2021
I though about adding 2 legends to my plots. One to display the entries that all plots share, and one that displays the entries that are unique for each plot.
I found a solution with copyobj, ( https://stackoverflow.com/questions/11253887/how-do-i-add-two-legends-to-a-single-plot-in-matlab ) however that only seems to work with Matlab versions older than 2014b or so.
Is there a solution for newer versions as well?
  2 Kommentare
mounika
mounika am 15 Nov. 2017
I am using R2017b, following worked perfectly fine for me:
%# create some plot with a legend
hAx(1) = axes();
hLine(1) = plot(1:10, 'Parent',hAx(1));
set(hAx(1), 'Box','off')
legend(hLine(1), 'line')
%# copy the axis
hAx(2) = copyobj(hAx(1),gcf);
delete( get(hAx(2),'Children') ) %# delete its children
hLine(2) = plot(sin(1:10), 'Color','r', 'Parent',hAx(2));
set(hAx(2), 'Color','none', 'XTick',[], ...
'YAxisLocation','right', 'Box','off') %# make it transparent
legend(hLine(2), {'curve'}, 'Location','NorthWest', 'Color','w')
Steineklopfer
Steineklopfer am 15 Nov. 2017
Hmm... Yeap you are right. It works for me too. Don't know why it didn't work when I found it.
Thanks :D

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Oindri
Oindri am 15 Nov. 2017
The code works fine on R2016a too. the legends appear on either top corners of the plot, since one is specifically mentioned 'northwest'
  1 Kommentar
Lee Key
Lee Key am 7 Mär. 2021
Bearbeitet: Lee Key am 7 Mär. 2021
I have same issue. I want to plot two different graphs (Yleft and Y right) on the same time series axis. When I run the code, the seond legend does not appear, only the first one. Any further help?
I used the location (northwest, and northeast, together with 'hold on'. Still I failed to have both legends on the plot.

Melden Sie sich an, um zu kommentieren.

Community Treasure Hunt

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

Start Hunting!

Translated by