nrow = 3;
ncol = 4;
ngrp = nrow*ncol;
x = rand(100,1);
y = rand(100,1);
group = ceil(rand(100,1)*ngrp);
datalabel = strtrim(cellstr(num2str((1:ngrp)', 'C%d')));
rowlabel = strtrim(cellstr(num2str((1:nrow)', 'Agent%d')));
collabel = strtrim(cellstr(num2str((1:ncol)', 'Temp%d')));
scatter(x,y,[],group);
cmap = parula(ngrp);
colormap(cmap);
set(gca, 'clim', [0 ngrp] + 0.5, 'ylim', [-0.5 1.5]);
hln = line(nan(2,ngrp), nan(2, ngrp), 'marker', 'o', 'linestyle', 'none');
set(hln, {'color'}, num2cell(cmap,2));
hplain = legend(hln(:), datalabel(:));
export_fig('leggrid1', '-png');
delete(hplain);
hr = line(nan(2,nrow), nan(2,nrow), 'linestyle', 'none');
hc = line(nan(2,ncol+1), nan(2,ncol+1), 'linestyle', 'none');
allobj = [hc'; [hr reshape(hln,nrow,ncol)]];
alllbl = ['-' collabel'; [rowlabel reshape(datalabel,nrow,ncol)]];
hleg1 = legendflex(allobj(:), alllbl(:), 'nrow', nrow+1, 'xscale', 0.5);
allobj = [hr reshape(hln,nrow,ncol)];
alllbl = [rowlabel reshape(datalabel,nrow,ncol)];
ttl = ['-' collabel'];
for ii = (ncol+1):-1:1
if ii == (ncol+1)
hleg2(ii) = legendflex(allobj(:,end), alllbl(:,end), 'ref', gca, ...
'anchor', {'se','se'}, 'buffer', [-10 10], 'xscale', 0.5, ...
'box', 'off', 'title', collabel{end});
else
hleg2(ii) = legendflex(allobj(:,ii), alllbl(:,ii), 'ref', hleg2(ii+1), ...
'anchor', {'sw','se'}, 'buffer', [0 0], 'xscale', 0.5, ...
'box', 'off', 'title', ttl{ii});
end
end