Adding Legend to a multiple graph within a loop

3 次查看(过去 30 天)
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

采纳的回答

Tommy
Tommy 2020-5-19
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 个评论
Tommy
Tommy 2020-5-19
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.

请先登录,再进行评论。

更多回答(0 个)

类别

Help CenterFile Exchange 中查找有关 Legend 的更多信息

标签

产品

Community Treasure Hunt

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

Start Hunting!

Translated by