
How to insert legend in plot after a for cycle?
9 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
Gaetano Zarcone
le 11 Jan 2020
Commenté : Star Strider
le 11 Jan 2020
I have a problem with the insertion of legend in a 3D plot in matlab. I have a list of data, in particular I have a nx3 matrix filled with data to plot and I want to separate these data by means of a discriminant. In my case the discriminant is time, so if i-th data is before the discriminant time it will be plotted in blue color, otherwise in red color. The code is
figure(1)
plot3(ra(1),dec(1),Time2plot(1),'*','Color','r', 'DisplayName', 'observation day');
hold on;
plot3(ra(end),dec(end),Time2plot(end),'*','Color','b','DisplayName', 'next day');
legend show;
for i = 1:length(Time2plot)
if timeofday(Time2plot(i)) > B(1) && timeofday(Time2plot(i)) < B(2)
hold on;
plot3(ra(i),dec(i),Time2plot(i),'*','Color', 'b');
else
hold on;
plot3(ra(i),dec(i),Time2plot(i),'*','Color','r');
end
end
hold on;
title(['RA Dec in 3D ', date(1,1)]);
xlabel('RA');
ylabel('Dec');
zlabel('Time');
ztickformat('HH:mm:ss');
grid on;
where B is discriminant time.
The result is

The issue is that I'd like only two line in legend: 'next day' and 'observation day' and not all data. Someone can help me?
0 commentaires
Réponse acceptée
Star Strider
le 11 Jan 2020
I cannot run your code, so here is a prototype you can adapt:
figure
hold on
for i = 1:10
hpb = plot3(rand, rand, rand, '*b','DisplayName', 'next day');
hpr = plot3(rand, rand, rand, '*r', 'DisplayName', 'observation day');
end
hold off
legend([hpb(1),hpr(1)])
grid on
view(-35,35)
producing:

The key to doing what you want is to return handles from the plot3 calls, then use only the first of each in the legend call.
2 commentaires
Star Strider
le 11 Jan 2020
My pleasure!
If my Answer helped you solve your problem, please Accept it!
Plus de réponses (0)
Voir également
Catégories
En savoir plus sur Legend dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!