Marker and Line in legend in matlab plot

108 次查看(过去 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.

采纳的回答

Walter Roberson
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
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
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 CenterFile Exchange 中查找有关 Legend 的更多信息

产品

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by