How do I include legend entries only for an array and not for each line of data?
10 visualizaciones (últimos 30 días)
Mostrar comentarios más antiguos
Kate P
el 31 de Ag. de 2023
Comentada: Star Strider
el 31 de Ag. de 2023
I'm plotting 48 lines of data but have them grouped by elevation, such that all datasets at one height are plotted the same color. I'd like to make a legend that has a single entry with the color and name of the elevation. With the code below it has 48 total legend entries (12 for each color). If I do legend('lower', 'lowermid', 'uppermid', 'upper'), then it will show these 4 legend entries to all have red lines (as the first 12 lines plotted are red). Is there a way to get around this without plotting one line of each color first to make the legend?
z4grid = gridTCdata(:,1:4:end);
z3grid = gridTCdata(:,2:4:end);
z2grid = gridTCdata(:,3:4:end);
z1grid = gridTCdata(:,4:4:end);
figure(1)
hold on
plot(z1grid,'color','red','DisplayName','lower')
plot(z2grid,'color','yellow','DisplayName','lowermid')
plot(z3grid,'color','green','DisplayName','uppermid')
plot(z4grid,'color','blue','DisplayName','upper')
legend
hold off

0 comentarios
Respuesta aceptada
Star Strider
el 31 de Ag. de 2023
Create handles for each plot call, and then use the first elements of those handles as the first argument to legend —
t = linspace(0, 2*pi);
z1grid = (1:5).'*sin(t);
z2grid = (1:5).'*sin(2*t) + 5;
z3grid = (1:5).'*sin(3*t) + 10;
z4grid = (1:5).'*sin(4*t) + 15;
figure
hold on
hp1 = plot(t,z1grid,'color','red','DisplayName','lower');
hp2 = plot(t,z2grid,'color','yellow','DisplayName','lowermid');
hp3 = plot(t,z3grid,'color','green','DisplayName','uppermid');
hp4 = plot(t,z4grid,'color','blue','DisplayName','upper');
hold off
legend([hp1(1) hp2(1) hp3(1) hp4(1)], 'Location','best')
.
2 comentarios
Más respuestas (0)
Ver también
Categorías
Más información sobre Legend en Help Center y File Exchange.
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!
