Add legend to multiple plots created by a for loop

조회 수: 2 (최근 30일)
Martin Muehlegger
Martin Muehlegger 2020년 1월 20일
답변: Rik 2020년 1월 20일
I create 15 scatter plots including 15 polyfit lines to each plot I would like to add a different legend.
str = {'Methanol', 'Acetonitrile','Acetaldehyde', 'Acetone','MBO fragment m69','Methyl_Ethyl-Ketone','Benzene',...
'a-Pinene fragment m81','Toluene','m-Xylene','1,3,5-Trimethylbenzene','a-Pinene','DMS','2-Methyl-3-buten-2-ol (MBO)',...
'1,2,4,5-Tetramethylbenzene'}
x = repmat(Dilution,1, length(Markeridx)); % 5x15
y = means(:,Markeridx)./conc; % 5x15
degree=1;
idx=1;
for m= 1:length(y)
figure('DefaultAxesFontSize',15); % outside the forloop gives single figures
% subplot(5, 4, idx);
hold all;
Scatter = scatter(x(:,m),y(:,m),20,'k','+');
p = polyfit(x(:,m),y(:,m),degree);
x_p = linspace(min(x(:,m)), max(x(:,m)));
y_p = polyval(p,x_p);
Fit = plot(x_p, y_p,'LineWidth',2);
% Place equation in upper left of graph.
xl = xlim;
yl = ylim;
xt = 0.05 * (xl(2)-xl(1)) + xl(1);
yt = 0.90 * (yl(2)-yl(1)) + yl(1);
set(gca,'TickLabelInterpreter','latex')
set(gcf,'units','points','position',[100,100,500,800]) % figure position on screen and size is the saved figuresize! [100,100,1500,800]
caption = sprintf('y = %f * x + %f', p(1), p(2));
text(xt, yt, caption, 'FontSize', 12, 'Color', 'k', 'FontWeight', 'bold','interpreter','latex');
xlabel('ppbv ','interpreter','latex'); %FC_cal/FC_zeroair *1000
ylabel('dcps','interpreter','latex');
idx = idx+1;
% lgd = legend(Scatter, num2str(m), 'Location','Southeast', 'AutoUpdate','off');
% lgd.FontSize = 8;
% lgd.Interpreter = 'latex';
end
legend(Scatter, str);
a = axes;
t1 = title('Gas calibration from 3\_08','interpreter','latex'); % Make sure to change titel after changing subsets
a.Visible = 'off'; % set(a,'Visible','off');
t1.Visible = 'on'; % set(t1,'Visible','on');
hold off;
Tried some things already,... this line
lgd = legend(Scatter, num2str(m), 'Location','Southeast', 'AutoUpdate','off');
within the for loop actually works but just gives me the index not the names from the string
str = {'Methanol', 'Acetonitrile','Acetaldehyde', 'Acetone','MBO fragment m69','Methyl_Ethyl-Ketone','Benzene',...
'a-Pinene fragment m81','Toluene','m-Xylene','1,3,5-Trimethylbenzene','a-Pinene','DMS','2-Methyl-3-buten-2-ol (MBO)',...
'1,2,4,5-Tetramethylbenzene'}
running MatLab2017b

채택된 답변

Rik
Rik 2020년 1월 20일
There are two ways to do this. Either you need to create an array of the handles to the scatter objects and use that in your call like you have in your current code, or you can set the DisplayName parameter when calling scatter, after which you can call legend without any arguments, or with the array of objects. (I didn't check if scatter supports this, but it probably does)

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