MATLAB: Colorbar with diamond-shape blocks

colorbarcustom legendgridplotpseudo legendshape

Hello,
I want to plot a colorbar with customized shapes. When I execute the colorbar command, I get the following colorbar in which each block is rectangular-shaped.
Screen Shot 2020-01-24 at 2.34.49 PM.png
However, I want to plot the colorbar in which each block has a diamond shape as shown in the following eample:
Screen Shot 2020-01-24 at 2.34.23 PM.png
Is it possible to customize the shape of the grid boxes like this?
Any help will be greatly appreciated.
Regards,
AG

Best Answer

Here are two methods to create a custom legend.
Method 1: Plot dummy variables that only appear in the legend.
plot(nan,nan,'d') will produce a point in the legend but won't appear in the axes.
clf()
axes() % main axis
hold on % important!
nMarkers = 10; % number of markers/colors

labels = 5:5:50; % legend labels
colors = jet(nMarkers); % Color of each marker (by row)

sh = arrayfun(@(i)scatter(nan,nan,50,colors(i,:),... % plot invisible markers
'd','filled','DisplayName',num2str(labels(i))),...
1:nMarkers);
legend(sh) % Specify invisible marker handles
If you'd rather use plot() instead of scatter(),
sh = arrayfun(@(i)plot(nan,nan,'d','Color','none',...
'MarkerFaceColor',colors(i,:),'DisplayName',...
num2str(labels(i))),1:nMarkers);
200124 181643-MATLAB Online R2019b.png
Method 2: Create a pseudo-legend on a separate axes
Produce a 2nd axes and use text() to label points.
clf()
axes('Position',[.1 .1 .7 .7]) % main axes
cbax = axes('position',[.83 .1 .05 .7]); % color legend axes
nMarkers = 10; % number of markers/colors
y = linspace(0.4,1,nMarkers); % y value of each marker
x = zeros(size(y)); % x value of each marker
labels = strsplit(strtrim(num2str(5:5:50))); % "legend" strings
colors = jet(nMarkers); % Color of each marker (by row)
scatter(cbax,x,y,50,colors,'d','filled') % plot the colored diamonds
ylim(cbax,[0,1]) % Scale the y axis for spacing
text(cbax,x+.4,y,labels,'FontSize',8) % Add the "legend" strings
axis(cbax,'off') % Turn off the legend axis
Related Question