MATLAB: Skip entries in a legend when plotting from a table

legendMATLABplotting

I have got a table from which I'd like to plot two fields ('Analysis' against 'Date'). The 'Analysis' field is a table itself, and I am plotting a particular field from it (PMkW_corr_298_RPMcorr). The health_monitor_log table has a field, 'Unit', from which I'd like to include unique values of in the legend. Each unique Unit has a different marker and/or colour.
I have tried the code below, but it doesn't seem to exclude repeat values of Unit from the legend. So for my first unique Unit entry, I'm expecting a triangle marker in the legend, and for the second unique Unit, a diamond. But when I type two entries for the legend in, I get two triangles, which is because the first two entries in the table have the triangle markers.
[c,ia,ic]=unique(health_monitor_log.Unit);
marker={'^','d','<','>','s','p','h'};
colour={'k','r','y','g','b','c','m'};
for i=1:size(health_monitor_log,1)
hold on
if any(strcmp('etath_PM_kW',fieldnames(health_monitor_log.Analysis{i,1})))
p=plot(health_monitor_log.Date(i),health_monitor_log.Analysis{i}.PMkW_corr_298_RPMcorr,'Marker',char(marker(health_monitor_log.Marker(i))),'MarkerFaceColor',char(colour(health_monitor_log.Colour(i))),'MarkerEdgeColor',[1,1,1])
if ~ismember(i,ia)
ant=get(p,'Annotation');
if iscell(ant)
for j=1:length(ant)
set(get(ant{j},'LegendInformation'),'IconDisplayStyle','off')
end
else
set(get(ant,'LegendInformation'),'IconDisplayStyle','off')
end
end
end
end

Best Answer

Solution was to restructure the table into a cell array ('plot_cell'), and use a handle array with 'DisplayName' property assigned to each handle as shown in How to show partial legend in figure
marker={'^','d','<','>','s','p','h'};
colour={'k','r','y','g','b','c','m'};
plot_cell=cell(size(health_monitor_log,1),1);
for i=1:size(health_monitor_log,1)
if any(strcmp('etath_PM_kW',fieldnames(health_monitor_log.Analysis{i,1})))
ss=health_monitor_log.Analysis{i};
ss.Date(:,1)=health_monitor_log.Date(i);
ss.Unit(:,1)=health_monitor_log.Unit(i);
ss.Marker(:,1)=health_monitor_log.Marker(i);
ss.Colour(:,1)=health_monitor_log.Colour(i);
plot_cell{i}=ss;
end
end
plot_cell=plot_cell(~cellfun('isempty',plot_cell));
h = zeros(size(plot_cell,1),1);
unit_names_list=repmat("String",size(plot_cell,1),1);
unique_unit_count=0;
for i=1:size(plot_cell,1)
unit_name=plot_cell{i}.Unit(1);
h(i)=plot(plot_cell{i}.Date,plot_cell{i}.PMkW_corr_298_RPMcorr,'Marker',...
char(marker(plot_cell{i}.Marker(1))),'MarkerFaceColor',...
char(colour(plot_cell{i}.Colour(1))),'MarkerEdgeColor',...
[1,1,1],'LineStyle','none','DisplayName',...
char(plot_cell{i}.Unit(1)));
hold on
if ~ismember(unit_name,unit_names_list)
unique_unit_count=unique_unit_count+1;
legend_idx(unique_unit_count)=i;
end
unit_names_list(i)=plot_cell{i}.Unit(1);
end
legend(h(legend_idx))