Select which legend entries to use depending on data set plotted

4 visualizzazioni (ultimi 30 giorni)
I have 5 data sets that I want to plot by using a for-loop.
All data sets are plotted in the same figure and a legend is used to distinguish between the different curves.
Each data set is taken from separate csv-files with different names.
In the best of worlds, all of the 5 data sets always exist and I can simply always use the legend below:
legendstr={'Position 1B','Position 2B','Position 3B','Position 4B','Position 5B'};
Lets say that the data set that should always be associated with "Position 2B", for example, does not exist. Then I simply do not want to see "Position 2B" in the legend. I don't care if its just replaced with a "-" or completely erased, I just do not want it in the legend.
However, the remaining legend entries should remain where the are, so when the data set for "Position 3B" is plotted, it gets the correct legend entry.
My problem right now is that when for example the data set for "Position 2B" does not exist, then there is a mismatch between the legend entries and the data they represent. For example when the data set for "Position 2B" does not exist, MATLAB simply puts the data set for "Position 3B" there instead and names it "Position 2B" in the legend, which i do not want it to do because its wrong.
How can I solve this problem? I have searched mathworks forum but not found a problem similar enough to mine.
If anyone wants to know, my entire code looks like:
clear
clc
positionletter=['A';'B'];
for packagenumber = [1:10] %FIRST 4 FOR LOOPS ARE JUST FOR DATA COLLECTION!
for positionnumber = [1:5]
for pos=[1:2]
filename=strcat('M1_G1_','P',num2str(packagenumber),'_',num2str(positionnumber),positionletter(pos),'_lf.csv');
if exist(filename,'file') == 0
continue
end
A = importdata(filename); %Importing the CSV file
package{packagenumber}{positionnumber}{pos} = A.data; %Naming the numerical array
time{packagenumber}{positionnumber}{pos}=package{packagenumber}{positionnumber}{pos}(:,1); %Biotac time vector is separated from package{i}
E_package{packagenumber}{positionnumber}{pos}=package{packagenumber}{positionnumber}{pos}(:,2:20); %Separating the sensors E1 through E19 from package{i}
PDC{packagenumber}{positionnumber}{pos}=package{packagenumber}{positionnumber}{pos}(:,21); %PDC array from CSV-file
globalforce{packagenumber}{positionnumber}{pos}=package{packagenumber}{positionnumber}{pos}(:,24); %Force array from CSV-file
x0=0;
y0=0;
width=800; %Setting height of figures
height=width * (8/11); % height to width ratio is 8:11 .
% figuresdir = strcat('D:\thesis_figures\M1_G1_','P',num2str(packagenumber),'_',num2str(positionnumber),positionletter(pos),'\'); %Creates the name of the folder in which the figures for each package will be put into
% mkdir(figuresdir); %The figure folder for each package is created
% addpath(figuresdir); %The figure folder for each package is added to the path so that MATLAB can actually put files in there
% figuresdir_forcepeaks_M3_G1 = strcat('D:\thesis_figures\figures_forcepeaks\M1_G1\'); %Folder name for force peak plots
% mkdir(figuresdir_forcepeaks_M3_G1);
% addpath(figuresdir_forcepeaks_M3_G1);
%
% [pks,locs] = findpeaks(globalforce{packagenumber}{positionnumber}{pos},time{packagenumber}{positionnumber}{pos}); %Creates vector for peaks and time locations for peaks
% peaks_package{packagenumber}{positionnumber}{pos}=pks;
% peaks_package_time{packagenumber}{positionnumber}{pos}=locs;
% figure_forcepeaks=strcat('M1','_','G1','_','P',num2str(packagenumber),'_',num2str(positionnumber),positionletter(pos));
% f_forcepeaks=figure('Name',figure_forcepeaks,'NumberTitle','off','Visible','off');
% % yyaxis left;
% title(['Forcepeaks M1_G1_','P',num2str(packagenumber),'_',num2str(positionnumber),positionletter(pos)]);
% xlabel('Time') ;
% findpeaks(globalforce{packagenumber}{positionnumber}{pos},time{packagenumber}{positionnumber}{pos},'MinPeakHeight',2)
% ylabel('Global force [N]') ;
% ylim([0 (max(globalforce{packagenumber}{positionnumber}{pos})+1)]); %The limits for the force range is set
% set(f_forcepeaks,'position',[x0,y0,width,height])
% saveas(f_forcepeaks,strcat(figuresdir_forcepeaks_M3_G1,figure_forcepeaks), 'png');
%
% forcepeaks_and_time=[pks,locs]';
%
% [forcepeak{packagenumber}{positionnumber}{pos} , peaklocation] = max(forcepeaks_and_time(1,:));
% peaktime{packagenumber}{positionnumber}{pos}=locs(peaklocation);
for i=1:19 %For each sensor indes, 1 through 19
E_norm{packagenumber}{positionnumber}{pos}(:,i)=((4095./E_package{packagenumber}{positionnumber}{pos}(:,i))-1)*10;%Creates an array of bit values from the sensors. Every cell in every column in E_temp is divided by the largest element in E_temp
end
end
end
end
%%
%FOLLOWING FOR-LOOPS ARE FOR PLOTTING ONLY
%M1_G1_290, contains 10 packages, 5 positions from A to B
for packagenumber =5%[5:10]
for pos=2%[1:2]
if pos==1
legendstr={'Position 1A','Position 2A','Position 3A','Position 4A','Position 5A'};
else
legendstr={'Position 1B','Position 2B','Position 3B','Position 4B','Position 5B'};
end
for i=2 %[2,3,5,7,8,9,10,12,13,15]
lengths=5000*ones(1,5);
for positionnumber=[1:5]
filename=strcat('M1_G1_','P',num2str(packagenumber),'_',num2str(positionnumber),positionletter(pos),'_lf.csv');
if exist(filename,'file') == 0
continue
end
lengths(1,positionnumber)=length(E_norm{packagenumber}{positionnumber}{pos}(:,i));
end
min_length=min(lengths);
times=(0:0.010:20);
common_time=times(1:min_length);
for positionnumber=[1:5]
filename=strcat('M1_G1_','P',num2str(packagenumber),'_',num2str(positionnumber),positionletter(pos),'_lf.csv');
if exist(filename,'file') == 0
continue
end
figuresdir = strcat('D:\thesis_figures\PositionComparison\M1_G1_290_','P',num2str(packagenumber),'_positions 1-5_',positionletter(pos),'\'); %Creates the name of the folder in which the figures for each package will be put into
mkdir(figuresdir); %The figure folder for each package is created
addpath(figuresdir); %The figure folder for each package is added to the path so that MATLAB can actually put files in there
% impedances_all=[E_norm{packagenumber}{1}{pos}(:,i)',... %This concatenates all impedance values
% E_norm{packagenumber}{2}{pos}(:,i)',...
% E_norm{packagenumber}{3}{pos}(:,i)',...
% E_norm{packagenumber}{4}{pos}(:,i)',...
% E_norm{packagenumber}{5}{pos}(:,i)'];
%
% y_min=min(impedances_all)-0.20; %The minimum y-value in the coming plot
% y_max=max(impedances_all)+0.20; %The maximum y-value in the coming plot
%%%%%%PLOTTING EACH E-SENSOR IMPEDANCE FOR SEVERAL POSITIONS IN ONE PLOT%%%%%%
E_norm_temp=E_norm{packagenumber}{positionnumber}{pos}(:,i);
E_norm_temp_truncated=E_norm_temp(1:min_length,1);
figurename=strcat('E ',num2str(i),' M1','_','G1','_','P',num2str(packagenumber),' positions 1-5 ',positionletter(pos));
f=figure(1);
hold on
plot(common_time,E_norm_temp_truncated);
%Plots all the impedance curves for the same sensor along different positions
ylabel('Biotac Impedance [k \Omega]');
title(['E',num2str(i),' M1',' ','G1 290gsm',' ','P',num2str(packagenumber),'_ ','positions 1-5 ',positionletter(pos)]);
xlabel('Time')
%ylim([y_min y_max]);
legend(legendstr);
set(f,'position',[x0,y0,width,height])
saveas(f,strcat(figuresdir, figurename), 'png');
end
end
end
end
Thank you!
  1 Commento
dpb
dpb il 23 Mar 2019
Answered the Q? asked below but...
...
figuresdir = strcat('D:\thesis_figures\PositionComparison\M1_G1_290_','P',num2str(packagenumber),'_positions 1-5_',positionletter(pos),'\'); %Creates the name of the folder in which the figures for each package will be put into
mkdir(figuresdir); %The figure folder for each package is created
%addpath(figuresdir); % folder added to the path so that MATLAB can actually put files in there
...
Do NOT add superfluous entries to the MATLAB path; use(*) fully-qualified filenames instead...
When create the output file name below, simply use
outfile=fullfile(figuresdir, [figurename 'png']);
and then use the variable outfile in the output function.
(*) Altho, in fact, you built a fully-qualified name anyway, just the slightly harder way with direct string manipulation; fullfile will gracefully handle the catenation whether the trailing slash is in the path name or not either adding if not or making sure isn't duplicated if is...

Accedi per commentare.

Risposta accettata

dpb
dpb il 23 Mar 2019
Modificato: dpb il 23 Mar 2019
...
for positionnumber=[1:5]
filename=strcat('M1_G1_','P',num2str(packagenumber),'_',num2str(positionnumber),positionletter(pos),'_lf.csv');
if ~exist(filename,'file'), continue, end % ==0 is superfluous; use NOT to negate for missing...
...
f=figure(1);
hold on
% save a line handle to mung with later if needed; add the corresponding legend string
hL(positionnumber,1)=plot(common_time,E_norm_temp_truncated,'displayname',legendstr(positionnumber));
...
%legend(legendstr);
end
legend; % turn legend on...
set(f,'position',[x0,y0,width,height])
saveas(f,strcat(figuresdir, figurename), 'png');
...
Looks to me as though the set and saveas belong after the 1:5 loop, not inside; otherwise you're saving file five times instead of just once after the figure is complete. I made that rearrangement above.
  2 Commenti
dpb
dpb il 23 Mar 2019
Alternatively, just define the labels dynamically since they're simply a constant string with the index number variable and the variable 'A' or 'B' suffix...
...
for positionnumber=[1:5]
...
legendstr=sprintf('Position %d%c',positionnumber,char('A'+ pos-1));
hL(positionnumber,1)=plot(common_time,E_norm_temp_truncated,'displayname',legendstr);
...
and you don't need the predefined arrays at all....

Accedi per commentare.

Più risposte (3)

Wojciech
Wojciech il 4 Ott 2021
Make vector composed of the handles of the plots:
h1=plot(x,y...
h2=plot(x2,y2,....
then use vector of these handles for selective legend
legend([h1,h2],'label1','label2'...)

David Goodmanson
David Goodmanson il 23 Mar 2019
Modificato: David Goodmanson il 25 Mar 2019
Hi Henry,
A simple way to do this is, when a trace does not exist, substitute it with nan(1,n) or nan(n,1), keeping the array the same size that it would have been. Replace the legend entry with something else, like a string of blanks ' '. This works, although it does display the trace color in the legend (which does not appear in the plot). That may or may not be a disadvantage, depending on whether you always want the same color associated with the same variable when going from plot to plot.

Image Analyst
Image Analyst il 23 Mar 2019
I'd keep track of what legends exist in a cell array, and just plot the whole thing after the array
legendCount = 0;
legendCollection = []; % Initialize to empty.
for i = 1 : 19
% If we NEED a legend for this one (you need to determine this):
legendCount = legendCount + 1; % Increment the number of legends we're having.
legendCollection{legendCount} = 'whatever string you want....' % Save a legend for this case, like legendstr{i} or whatever
end
if ~isempty(legendCollection)
legend(legendCollection); % Display ONLY the ones where we saved a legend for.
end

Prodotti


Release

R2018a

Community Treasure Hunt

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

Start Hunting!

Translated by