필터 지우기
필터 지우기

Adding Legend to a multiple graph within a loop

조회 수: 3 (최근 30일)
Nico Pisani
Nico Pisani 2020년 5월 19일
댓글: Nico Pisani 2020년 5월 20일
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.
Nico Pisani
Nico Pisani 2020년 5월 20일
Thank you, Tommy. This helps!
Cheers!

댓글을 달려면 로그인하십시오.

추가 답변 (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