How do I include legend entries only for an array and not for each line of data?
12 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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 commentaires
Réponse acceptée
Star Strider
le 31 Août 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 commentaires
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Legend dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!