How do I include legend entries only for an array and not for each line of data?
29 ビュー (過去 30 日間)
古いコメントを表示
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 件のコメント
採用された回答
Star Strider
2023 年 8 月 31 日
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')
.
その他の回答 (0 件)
参考
カテゴリ
Help Center および File Exchange で Legend についてさらに検索
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!