MATLAB Answers


Using imagesc to make a matrix a heatmap, how can I mark an 'x' inside the cell of max value of each column?

Asked by Michael Jones on 23 May 2019
Latest activity Edited by Adam Danz
on 23 May 2019
I have created a checkerboard heatmap with imagesc, using 9 subplots for an 11x11x9 array. I would like to clearly denote the 'maximum value' in each column with a red 'x' placed inside the center of each cell.
Below is the code I run to (successfully) generate the subplots. The commented section is my failed attempt to start drawing these 'x' markers - hoping for some help. Thank you!
[max_val, ~] = max(cond_npvnetrevcumlist_btfc0_417_extinct(:));
maxcaxis = max_val;
[min_val, ~] = min(cond_npvnetrevcumlist_btfc0_417_extinct(:));
mincaxis = min_val;
for k=1:9
title(['Initial Bt Resistance Alleles=' num2str(InitResistList(k)*100) '%'])
ylabel('% Bt Planted')
xlabel('GM DBM release rates')
ticknumx = linspace(0,12,13);
ticknumy = linspace(0,11,12);
xticklabels({'0','0', '0.5', '1', '1.5', '2', '4', '6', '10', '15', '20', '40'})
c.Label.String = '% Max Revenue, net seed+releases';
caxis([mincaxis,maxcaxis]) %Engage to equate across all colorbar values; makes it harder to see the max within each matrix though
% %Failed attempt thus far to draw an 'x' in the centroid of the matrix cell of each column maximum value
% markers = zeros(11,1);
% for m=1:11
% [~, max_val_col] = max(cond_npvnetrevcumlist_btfc0_417_extinct(:,m,k));
% markers(m)= max_val_col;
% end
% pos=zeros(11,2);
% for n=1:11
% pos(n,1)=n;
% pos(n,2)=markers(n);
% end
% color={'magenta'};
% RGB=insertMarker(I,pos,'x','color',color);


Sign in to comment.

1 Answer

Answer by Adam Danz
on 23 May 2019
Edited by Adam Danz
on 23 May 2019
 Accepted Answer

Here's a simpler version that uses an "X" in text format. Just replace my fake "C" with your real data.
C = magic(9);
I = imagesc(C);
% Find row with max val for each col
[~, maxRowIdx] = max(I.CData,[],1);
% Assign text
text(1:size(C,2), maxRowIdx, repmat({'X'},size(maxRowIdx)), ...
'VerticalAlignment', 'Middle','HorizontalAlignment', 'Center', ...
'FontSize', 14, 'FontWeight', 'Bold')
If your columns and rows start at values other than 1, you'll need to slightly adapt this by offsetting the (x,y) coordinates. use the I.XData and I.YData for rescaling the coordinates.