How to add a legend for a plot generated with a function multiple times?

조회 수: 7 (최근 30일)
I am working with orbits around Earth. To plot them, I use a function with the orbital parameters as input. My problem is that I don't know how to create a legend when calling the function more than one time to show on the same plot multiple orbits.
Adding a legend manually like this
plotOrbit(a, e, i, OM, om, th0, thf, dt, mu)
plotOrbit(a1, e1, i1, OM1, om1, th0, thf, dt, mu)
legend("Initial orbit", "Final orbit")
give me a wrong line for the second orbit. (It should be orange instead of a random blue tiny line).
I tried to follow a different approach
txt = 'Initial orbit';
plotOrbit(a, e, i, OM, om, th0, thf, dt, mu, txt)
txt = 'Final orbit';
plotOrbit(a1, e1, i1, OM1, om1, th0, thf, dt, mu, txt)
legend show
Adding this line in the function script
plot3(r(1, :), r(2, :), r(3, :), 'DisplayName',txt, LineWidth=2)
Now the legend shows the right lines, but the result shows 4 extra labels that I don't know how to remove.
ù
Do you know how to solve this? Thank you
  댓글 수: 2
Steven Lord
Steven Lord 2023년 4월 14일
It's going to be difficult to offer any specific suggestions without seeing what your plotOrbit function is doing.
Niccolò Bruno
Niccolò Bruno 2023년 4월 14일
Even if @Antoni Garcia-Herreros helped me already, I add the function for completeness.
function plotOrbit(a, e, i, OM, om, th0, thf, dt, mu)
r = [];
for t = th0:dt:thf
r = [r, parorb2rv(a, e, i, OM, om, t, mu)];
end
% this gives the position in a cartesian frame in the form r = [x; y; z]
figure(1)
plot3(r(1, :), r(2, :), r(3, :), LineWidth=2)
axis equal; % Make the axes scales match
title("Orbits");
hold on; % Add to the plot
Terra3d %function to add the 3d model of the Earth
end

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

채택된 답변

Antoni Garcia-Herreros
Antoni Garcia-Herreros 2023년 4월 14일
편집: Antoni Garcia-Herreros 2023년 4월 14일
Hello,
As @Steven Lord pointed out it's hard to suggest anything without knowing how plotOrbit works, but you could try something like this:
plotOrbit(a, e, i, OM, om, th0, thf, dt, mu)
plotOrbit(a1, e1, i1, OM1, om1, th0, thf, dt, mu)
l=legend('Initial orbit','','','Final orbit');

추가 답변 (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