2 different legend on the same graph for the same data

조회 수: 5 (최근 30일)
Irad Brandys
Irad Brandys 2024년 6월 15일
댓글: Irad Brandys 2024년 6월 16일
I have a code which generates 2 plots with the same y-axes and x-axes values (see attached figures).
how can I plot only one figure but with the two different legends ?
attached below is my first plot code. the second code lines are similar but they create new plot and the new legend.
10x in advance,
Irad
for j=1:dpointsnum
plot(totxdata,totydata1(j,:),'linestyle',getprop(lines,1),...
'Color',getprop(colors,j)); hold on;
end
grid(gca,'minor');
xlabel('n\cdotM','FontName','Arial','FontWeight','bold','FontSize',12);
ylabel('Ductility ratio, \mu', FontSize=12,FontWeight='bold',FontName='Arial');
nLeg = legend(Leg); %adding legend entries to the plot
nLeg.Title.String = {'Scaled distance';'[m/kg^{1/3}]'}; %adding title to the lgened
  댓글 수: 1
Irad Brandys
Irad Brandys 2024년 6월 16일
thank you very much. was very helpful.
And how can I add a title to each one of the legends ?
I tried to use for e.g.
title(leg1,'chk1')
but recieved 'Invalid argument. Type 'help legend' for more information'
Irad

댓글을 달려면 로그인하십시오.

답변 (1개)

Ganesh
Ganesh 2024년 6월 15일
편집: Ganesh 2024년 6월 15일
You can usually have only 1 legend per plot. However, you can use a small workaround to make two overlapping plots, and plot two legends for each of them with different units as you require. Kindly follow the below code demo:
x = linspace(0, 10, 15);
y1 = rand(1, 15) * 10;
y2 = rand(1, 15) * 10;
y3 = rand(1, 15) * 10;
hold on
p = plot(x, y1, 'r', x, y2, 'g', x, y3, 'b'); % 'r' is red, 'g' is green, 'b' is blue
p2 = plot(x, y1, 'r', x, y2, 'g', x, y3, 'b') ;
title('Demo Plot')
xlabel('X axis')
ylabel('Y axis')
hold off
grid off
leg1=legend(p,'Unit1A', 'Unit1B', 'Unit1C','Location','NorthEast');
set(leg1,'FontSize',9);
ah1=axes('position',get(gca,'position'),'visible','off');
leg2=legend(ah1,p2,'Unit2A', 'Unit2B', 'Unit2C','Location','NorthWest');
set(leg2,'FontSize',9);
Though I have put in the "Labels" as a part of the function, you could create a variable for the labels and use it in the function.
The legend fuction has more options you could tweak, which you can find in the following documentation:
Hope this helps!

카테고리

Help CenterFile Exchange에서 Legend에 대해 자세히 알아보기

제품


릴리스

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by