legend - How To Label Colormaps in MATLAB? -


i have following image derived imagesc(some matrix entries correspond colors). cyan , yellow both mean different things. either:

  1. add legend can fill in each color means

  2. segregate parts of x-axis can type "cyan" on x region below cyan part, , "yellow" on x region below yellow part.

either or fine, , ever 1 easier appropriate me.

enter image description here

                cyan                         yellow 

here's option, happens friendly:

%% // initialization clear variables; close force; clc; %% // generate data fakedata = magic(3)-0.5; fakedata_horz = fakedata(:)'; %//' fakenames = cellstr(strcat('color',num2str((1:9)'))); %//' fakenamemapping = fakenames(randperm(numel(fakedata))); %% // create figure hfig = figure('position',[680,488,758,610],'resize','off');  %% // top left example clims = [0 numel(fakedata)+1]; hsp = subplot(2,2,1);  imagesc(fakedata); axis image; set(hsp,'xtick',[],'ytick',[]); colorbar; caxis(clims);  [xx,yy] = meshgrid(1:size(fakedata,1),1:size(fakedata,2)); text(xx(:),yy(:),fakenamemapping,'horizontalalignment','center');  %% // bottom example hsp = subplot(2,2,3:4); clims = [0 numel(fakedata)+1]; %not required here since unchanged imagesc(fakedata_horz); axis image; set(hsp,'xtick',[],'ytick',[]); colorbar; caxis(clims);  drawnow; %// command allow annotations positioned ind1=1:numel(fakedata_horz)     newpos = [hsp.position(1)+hsp.position(3)/numel(fakedata_horz) * (ind1-1),...               hsp.position(2)*1.6,... %1.6 chosen demo               hsp.position(3)/numel(fakedata_horz),...               0.05]; % 0.05 chosen demo; play around     h= annotation('textbox',newpos,'string',fakenamemapping{ind1},...         'linestyle','none','horizontalalignment','center'); end  %% // top right example hsp = subplot(2,2,2); clims = [0 numel(fakedata)]; %// clims bit different here! imagesc(fakedata); axis image; set(hsp,'xtick',[],'ytick',[]); caxis(hsp,clims); colormap(hsp,parula(numel(fakedata))); cb = colorbar; %// time need handle colorbar cb.ticks = (hsp.clim(1):hsp.clim(2))+0.5; %// set tick positions cb.ticklabels = fakenames; %// set tick strings 

which results in: enter image description here

note: unless using more intelligent text positioning computation, figure's size should not changed after plotted (in 2nd example), because text no longer remains should be.


edit: added option colorbar labeled.


Comments