Displaying legend for multiple plots

I haven't seen this question asked yet, so I guess the solution is quite simple, but I haven't been able to find it.
I need to plot several groups of lines (each of about 10-15 lines) and display legend, but not for each of the lines seperately but only for each group.
Specificaly, I have groups of impact craters arranged by the age of the surface they are on. Each group has around20-30 craters and there are 4 groups, so I want the legend of the graph to have 4 entries, one for each group.
Can someone help me with this? Thank you in advance.

 Respuesta aceptada

Luffy
Luffy el 7 de Jul. de 2012
Editada: Luffy el 7 de Jul. de 2012
h = get(gca,'Children');
Then select handles of lines you want to add to legend.
Say h(1) is handle of a line in 1st group,
h(10) 2nd group,
h(15) 3rd
h(30) 4th
v = [h(1) h(10) h(15) h(30)]';
legend(v);

3 comentarios

Marin
Marin el 7 de Jul. de 2012
Can you please clarify a bit more? Say for example I want to use this on this code:
a=randn(5,50);
b=randn(5,50);
c=randn(5,50);
figure
for i=1:5
plot(a(i,:),'.-b')
hold on
plot(b(i,:),'.-r')
hold on
plot(c(i,:),'.-g')
hold on
end
How would I do that? does the 'set' go inside the for loop? Also, I never used handles before, how do I "select hadles of lines"?
Sorry for the noob questions, I'm still quite new at Matlab. :)
Thank you
Marin
Marin el 7 de Jul. de 2012
Excellent, thank you very much!
Luffy
Luffy el 7 de Jul. de 2012
You need not use hold on command that many times,just write it before for loop,after figure command

Iniciar sesión para comentar.

Más respuestas (1)

Luffy
Luffy el 7 de Jul. de 2012
Editada: Luffy el 7 de Jul. de 2012
a=randn(5,50);
b=randn(5,50);
c=randn(5,50);
figure;
hold on;
for i=1:5
plot(a(i,:),'.-b');
plot(b(i,:),'.-r');
plot(c(i,:),'.-g');
end
h = findobj('Color','r');
g = findobj('Color','b');
i = findobj('Color','g');
v = [h(1) g(1) i(1)];
legend(v);
% For location where your legend should appear see
doc legend

2 comentarios

Marin
Marin el 7 de Jul. de 2012
I see. I tought that hold on should go after every plot we wish to add. Thank you once again :)
mimi sam
mimi sam el 22 de Mayo de 2017
Or you can proceed as in this example (of matlab)
Plot three lines and return the chart line objects created. Then, create a legend that includes only two of the lines by specifying the first input argument as a vector of the chart line objects to include.
x = linspace(0,3*pi); y1 = sin(x); p1 = plot(x,y1);
hold on y2 = sin(x - pi/4); p2 = plot(x,y2);
y3 = sin(x - pi/2); p3 = plot(x,y3); hold off
legend([p1 p3],'First','Third')

Iniciar sesión para comentar.

Preguntada:

el 17 de Abr. de 2012

Comentada:

el 22 de Mayo de 2017

Community Treasure Hunt

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

Start Hunting!

Translated by