How do I include legend entries only for an array and not for each line of data?
12 次查看(过去 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!