Marker and Line in legend in matlab plot
181 ビュー (過去 30 日間)
古いコメントを表示
Hi, I am plotting the experimental data and fitted line using matlab plot. The legend command shows the markers (data points) and line (fit) as a separate legend entry. However, I am interested to obtain the marker and line in a single legend entry so that the total number of legend entries could be reduced from 8 to 4 in my case. Hence, I would like to ask your assistance which could be useful for my plot. Thank you.
0 件のコメント
採用された回答
Walter Roberson
2016 年 4 月 6 日
Create additional line objects that combine the attributes, such as
LH(1) = plot(nan, nan, '*-r');
L{1} = 'tadpoles';
LH(2) = plot(nan, nan, '^:g');
L{2} = 'cheese';
Then legend() those
legend(LH, L)
8 件のコメント
Olivier Haas
2023 年 4 月 21 日
編集済み: Olivier Haas
2023 年 4 月 21 日
Displaying appropriate markers in legend when plotting 2D arrays against 1D array.
% create array data
D1=rand(500,12);
D2=rand(500*0.15,12);
t=[7:18];
% plot array data where each columm correspond to one element of the x vector
figure(1),clf
subplot(121)
p1=plot(t,D1,'g.');hold on
p2=plot(t,D2,'+k');
legend([p1(1),p2(1)],'100% cars EV','15% cars EV');
% to be able to display each marker for D1 and D2 need to use plot handle
% for one of the data plotted in each plot => (1)
subplot(122)
plot(t,D1,'g.');hold on
plot(t,D2,'+k');
legend('100% cars EV','15% cars EV');
% without using plot handle in the legend command you can only see the same
% marker
Walter Roberson
2023 年 4 月 21 日
Yes, that is expected. When you call legend() and do not pass in handles of graphics objects, then it looks to see how many legend entries you supplied (two in this case) and it finds the first that-many (so, first 2 in this case) graphics objects and creates legends for those. Your plot(t,D1,'g.') is creating multiple graphics objects because D1 is a 2D array, so the first two graphic handles are both associated with D1.
If you want to create one legend entry for each line in D1 then you can do that:
% create array data
D1=rand(500,12);
D2=rand(500*0.15,12);
t=[7:18];
% plot array data where each columm correspond to one element of the x vector
figure(1),clf
subplot(121)
p1=plot(t,D1,'g.');hold on
p2=plot(t,D2,'+k');
legend([p1(1),p2(1)],'100% cars EV','15% cars EV');
% to be able to display each marker for D1 and D2 need to use plot handle
% for one of the data plotted in each plot => (1)
subplot(122)
p3 = plot(t,D1,'g.');hold on
p4 = plot(t,D2,'+k');
L3 = "100% cars EV #" + (1:length(p3)).';
set(p3, {'DisplayName'}, cellstr(L3));
L4 = "15% cars EV #" + (1:length(p4)).';
set(p4, {'DisplayName'}, cellstr(L4));
legend([p3; p4], 'location', 'eastoutside', 'NumColumns', 4)
その他の回答 (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!