How to insert legend in plot after a for cycle?

20 ビュー (過去 30 日間)
Gaetano Zarcone
Gaetano Zarcone 2020 年 1 月 11 日
コメント済み: Star Strider 2020 年 1 月 11 日
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
pp.jpg
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?

採用された回答

Star Strider
Star Strider 2020 年 1 月 11 日
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:
1How to insert legend in plot after a for cycle - 2020 01 11.png
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 件のコメント
Gaetano Zarcone
Gaetano Zarcone 2020 年 1 月 11 日
Thank you very much Star Strider. It works!!
Star Strider
Star Strider 2020 年 1 月 11 日
My pleasure!
If my Answer helped you solve your problem, please Accept it!

サインインしてコメントする。

その他の回答 (0 件)

カテゴリ

Help Center および File ExchangeLegend についてさらに検索

Community Treasure Hunt

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

Start Hunting!

Translated by