2 different legend on the same graph for the same data

5 Ansichten (letzte 30 Tage)
Irad Brandys
Irad Brandys am 15 Jun. 2024
Kommentiert: Irad Brandys am 16 Jun. 2024
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 Kommentar
Irad Brandys
Irad Brandys am 16 Jun. 2024
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

Melden Sie sich an, um zu kommentieren.

Antworten (1)

Ganesh
Ganesh am 15 Jun. 2024
Bearbeitet: Ganesh am 15 Jun. 2024
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!

Produkte


Version

R2023b

Community Treasure Hunt

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

Start Hunting!

Translated by