Effacer les filtres
Effacer les filtres

Adding Legend to a multiple graph within a loop

3 vues (au cours des 30 derniers jours)
Nico Pisani
Nico Pisani le 19 Mai 2020
Commenté : Nico Pisani le 20 Mai 2020
Hello there!
I am writing a short code for plotting data from COMSOL.
These data concern the attenuation loss of a bent loss for fifteen curvature radii against twenty-seven wavelength forming a 405 X 3 matrix. I need to overlay each plot within the same image and to label each one by the relative curvature radius. I succeeded to complete the first part of the task but I really cannot add the legends. Could anyone please help me?
clear all
close all
clc
hold on
data=dlmread('data.txt')
for i= 1:27:378
for j = 28:27:405
for k=1:15
txt = ['X = ',num2str(k)];
plot(data(i:j,2),data(i:j,3), 'DisplayName' ,txt)
end
end
end

Réponse acceptée

Tommy
Tommy le 19 Mai 2020
The legend should show after you call legend(), i.e.:
clear all
close all
clc
hold on
data=dlmread('data.txt')
for i= 1:27:378
for j = 28:27:405
for k=1:15
txt = ['X = ',num2str(k)];
plot(data(i:j,2),data(i:j,3), 'DisplayName' ,txt)
end
end
end
legend
But I believe this will create 14*14*15 = 2940 separate line plots. Are you possibly aiming for this instead?
plot(data(1:27,2),data(1:27,3), 'DisplayName', ['X = 1'])
plot(data(28:54,2),data(28:54,3), 'DisplayName', ['X = 2'])
.
.
.
plot(data(379:405,2),data(379:405,3), 'DisplayName', ['X = 14'])
If so, you could use this:
hold on
data=dlmread('data.txt')
for k = 1:15
txt = ['X = ',num2str(k)];
i = 27*(k-1)+1;
j = 27*k;
plot(data(i:j,2),data(i:j,3),'DisplayName',txt)
end
legend
  3 commentaires
Tommy
Tommy le 19 Mai 2020
Happy to help!
Sure, you can set the Color when calling plot:
hold on
data=dlmread('data.txt')
colors = rand(15,3);
for k = 1:15
txt = ['X = ',num2str(k)];
i = 27*(k-1)+1;
j = 27*k;
plot(data(i:j,2),data(i:j,3),'DisplayName',txt,'Color',colors(k,:))
end
legend
This just creates 15 random RGB triplets. You could set them yourself to specific colors if you'd like, or you could use a colormap to generate the RGB triplets.
Nico Pisani
Nico Pisani le 20 Mai 2020
Thank you, Tommy. This helps!
Cheers!

Connectez-vous pour commenter.

Plus de réponses (0)

Tags

Produits

Community Treasure Hunt

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

Start Hunting!

Translated by