Coloring curves wrt to a third variable and creating legend for the same

1 vue (au cours des 30 derniers jours)
Hems
Hems le 10 Fév 2018
Commenté : Greg le 13 Fév 2018
Hello, I need to plot 31 curves and their color needs to be according to a third variable that varies from 1 to 5. I tried writing the code as follows:
colorspec1 = colormap(jet(5));
for i = 1:31
for j = 1:5
if MA(i,2) == j
semilogx(All_112(:,1), All_112(:,i+1),'-', 'Linewidth', 2, 'Color', colorspec1(j,:));
hold all
end
legendInfo{j} = ['Wind Speed = ' num2str(j)];
end
end
legend(legendInfo);
I am getting curves with varying colors, but something is wrong with the code as when I change the loop positions and define j before i, the color of some curves also changes, which should not happen. I am unable to fix this issue and would need your help. Another issue is that I need a legend with 5 different colored lines in the colormap to define the third variable, but unable to get that with this version of the code. Could you please give me some direction how to do that? Thanks.
  6 commentaires
Hems
Hems le 10 Fév 2018
No worries. Thank you very much for your help. It works with plot.
Greg
Greg le 13 Fév 2018
My updated answer should better solve the down-selected legend. There's a chance it isn't compatible with your release of MATLAB; I'm not sure when the behavior of legend I'm taking advantage of was added.

Connectez-vous pour commenter.

Réponse acceptée

Greg
Greg le 10 Fév 2018
Modifié(e) : Greg le 13 Fév 2018
There's no reason to loop over colors - you already have the index in MA(i,2). Assuming the second column of MA is restricted to 1:5, use this:
colorspec1 = colormap(jet(5));
hline = gobjects(31,1);
for ii = 1:31
icolor = MA(ii,2);
hline(ij) = semilogx(All_112(:,1),All_112(:,ii+1),'-', ...
'Linewidth',2,'Color',colorspec1(icolor,:), ...
'DisplayName',sprintf('Wind speed = %d',icolor));
hold all
end
[~,inds] = unique(MA(:,2));
legend(hline(inds));
  6 commentaires
Hems
Hems le 13 Fév 2018
Hi Greg, this works perfectly. Thanks a lot.
Greg
Greg le 13 Fév 2018
Happy to help!

Connectez-vous pour commenter.

Plus de réponses (0)

Catégories

En savoir plus sur Blue 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!

Translated by