How to use one marker for looped plots in legend

16 vues (au cours des 30 derniers jours)
Jianchuan Tan
Jianchuan Tan le 22 Sep 2021
Commenté : Jianchuan Tan le 22 Sep 2021
Hi All,
I am trying to plot a large number of points in loops, but there are only 4 categories. Each category has a specific marker: 'bx', 'r.', 'g.', and 'k+'. You can see the plotting results below:
But in the legend, I got only one type of marker ('bx') for all the categories. I need the latter 3 categories to have markers of 'r.', 'g.' and 'k+', respectively.
Below is my code:
figure(2)
for j = 1:size(s_ph1,2)
scatter(s_ph1(:,j),t_ph1(:,j),'bx'); hold on;
end
for j = 1:size(spds_ph2,2)-1
scatter(s_ph2_optmean(:,j),t_ph2_optmean(:,j),'r.'); hold on;
scatter(s_ph2_optrms(:,j),t_ph2_optrms(:,j),'g.'); hold on;
end
for j = 1:length(s_sl_bl2)
plot(s_sl_bl2(j),t_sl_bl2(j),'k+','MarkerSize',5,'LineWidth',1); hold on;
text(s_sl_bl2(j)+0.01,t_sl_bl2(j)+0.01,string(wl2(j))); hold on;
end
for j = 1:length(s_pl_bl2)
plot(s_pl_bl2(j),t_pl_bl2(j),'k+','MarkerSize',5,'LineWidth',1); hold on;
text(s_pl_bl2(j)+0.003,t_pl_bl2(j)+0.003,string(cct2(j))); hold on;
end
legend('Original Transform','Mean-Opt Transform','RMS-Opt Transform','Baseline (2015 10^{\circ})'); hold on;
title('All points');
xlabel('s');
ylabel('t');
hold off;
Can anyone help me fix it? Thanks a lot!
JT

Réponse acceptée

Star Strider
Star Strider le 22 Sep 2021
I cannot run the posted code, however the solution may be straightforward.
figure
hold on
for k = 1:50
hs{1} = scatter(rand,rand,'r.');
end
for k = 1:60
hs{2} = scatter(rand, rand,'.g');
end
hold off
legend([hs{1}(1),hs{2}(1)], 'Series 1', 'Series 1')
Use handles in each scatter call, and the refer to them appropriately in the legend call.
Experiment to get the result you want.
.

Plus de réponses (1)

Bjorn Gustavsson
Bjorn Gustavsson le 22 Sep 2021
To get full controll of legends use the graphics-handles that are returned from the plot-functions. Perhaps something like this:
figure(2)
for j = 1:size(s_ph1,2)
ph1 = scatter(s_ph1(:,j),t_ph1(:,j),'bx'); hold on;
end
for j = 1:size(spds_ph2,2)-1
ph2 = scatter(s_ph2_optmean(:,j),t_ph2_optmean(:,j),'r.'); hold on;
ph3 = scatter(s_ph2_optrms(:,j),t_ph2_optrms(:,j),'g.'); hold on;
end
for j = 1:length(s_sl_bl2)
ph4 = plot(s_sl_bl2(j),t_sl_bl2(j),'k+','MarkerSize',5,'LineWidth',1); hold on;
text(s_sl_bl2(j)+0.01,t_sl_bl2(j)+0.01,string(wl2(j))); hold on;
end
for j = 1:length(s_pl_bl2)
ph5 = plot(s_pl_bl2(j),t_pl_bl2(j),'k+','MarkerSize',5,'LineWidth',1); hold on;
text(s_pl_bl2(j)+0.003,t_pl_bl2(j)+0.003,string(cct2(j))); hold on;
end
legend([ph1(1),ph2(2),ph3(1),ph4(1)],...
'Original Transform',...
'Mean-Opt Transform',...
'RMS-Opt Transform',...
'Baseline (2015 10^{\circ})');
hold on;
title('All points');
xlabel('s');
ylabel('t');
hold off;
HTH

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by