2 different legend on the same graph for the same data

6 次查看(过去 30 天)
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