Clear Filters
Clear Filters

How do i add legend to a single figure with plots from multiple sheets of two different excel files?

1 view (last 30 days)
I have two excel files with different sheets, data from which I have plotted in one figure. Plots from different excel files are differentiated by different colors and sheets from same excel file by different line styles. But, I am struggling with giving legends in this figure. I would like to have legends of all the plots in color of their lines with description as their line style and marker. My code is as follows. Please suggest how can i solve the issue with legends
filename1 = '*.xlsx'; filename2= '**.xlsx';
sheetnames1 = { 'Tabelle1','Tabelle2','Tabelle3','Tabelle4' }; sheetnames2 = { 'Tabelle1','Tabelle2','Tabelle3'};
n = length(sheetnames1); m = length(sheetnames2);
linS = {'-',':','-.','--'}; plotlineMarker = {'<','+','o','x'}; plotlineLegend={'100','200','300','400'};
Legend1=cell(4,1); legend2=cell(3,1);
hold all
for i = 1:n a = xlsread(filename1,sheetnames1{i}); plot (a(:,1),a(:,4),'color','g','Linestyle',linS{i},'Marker',plotlineMarker{i}); Legend1{i} = strcat(linS{i},plotlineMarker{i},plotlineLegend{i}); end
legend(Legend1);
for j = 1:m b = xlsread(filename2,sheetnames2{j}); plot (b(:,1),b(:,4),'color','r','Linestyle',linS{j},'Marker',plotlineMarker{j}); legend2{j} = strcat(linS{j},plotlineMarker{j},plotlineLegend{j}); end
legend(Legend2);
title('***'); xlabel('****') ylabel('*****');

Answers (1)

Matt Sprague
Matt Sprague on 11 Jan 2018
An Axes object can have only one legend. Assuming you want to have the legend display information from both excel files data, you can combine each cell array in a single call to the "legend" function. See the example below:
filename1 = '*.xlsx';
filename2= '**.xlsx';
sheetnames1 = { 'Tabelle1','Tabelle2','Tabelle3','Tabelle4' };
sheetnames2 = { 'Tabelle1','Tabelle2','Tabelle3'};
n = length(sheetnames1);
m = length(sheetnames2);
linS = {'-',':','-.','--'};
plotlineMarker = {'<','+','o','x'};
plotlineLegend={'100','200','300','400'};
legend1=cell(4,1); legend2=cell(3,1);
hold all
for i = 1:n
a = xlsread(filename1,sheetnames1{i});
plot (a(:,1),a(:,4),'color','g','Linestyle',linS{i},'Marker',plotlineMarker{i});
legend1{i} = plotlineLegend{i};
end
for j = 1:m
b = xlsread(filename2,sheetnames2{j});
plot (b(:,1),b(:,4),'color','r','Linestyle',linS{j},'Marker',plotlineMarker{j});
legend2{j} = plotlineLegend{j};
end
legend([legend1; legend2]);

Community Treasure Hunt

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

Start Hunting!