Reputation: 65
I want to add a marker/special tick mark in my MATLAB colorbar
. For example, lets say I have a colorbar scale from -2
to 3
and my critical value is -1.8
, how can I add a marker of the value by symbol/marker?
Upvotes: 3
Views: 1680
Reputation: 125874
One way to do this is to fetch the colorbar position, compute the location where you want your marker, and place an annotation object (like an arrow) there:
% Plot sample data, displaying color bar and getting its limits:
data = peaks();
imagesc(data);
hBar = colorbar();
cLimits = caxis();
hold on;
% Select and plot a point of interest:
point = [31 15];
value = data(point(1), point(2));
plot(point(2), point(1), 'r+');
% Compute location of color bar pointer and make annotation:
barPos = get(hBar, 'Position');
xArrow = barPos(1)+barPos(3)/2+[0.05 0];
yArrow = barPos(2)+barPos(4)*(value-cLimits(1))/diff(cLimits)+[0 0];
hArrow = annotation('textarrow', xArrow, yArrow, ...
'String', num2str(value, '%.2f'), 'Color', 'r');
If the figure is resized, the position of the annotation object may shift with respect to the color bar. One way to avoid this is to tweak the axes and color bar resize behavior with the following code:
axesPos = get(gca, 'Position');
set(hBar, 'Location', 'manual');
set(gca, 'Position', axesPos);
This should allow the annotation object to stay fixed to the proper spot over the color bar.
Upvotes: 4
Reputation: 10450
Here is yet another option - just add/change the tick label at the specific value:
MarkTxt = '<-Mark';
imagesc(rand(10)-2) % something to plot
colormap('jet')
CB = colorbar;
% in case you DON'T want the value to appear:
value = -1.8;
t = find(CB.Ticks==value);
if ~isempty(t)
CB.TickLabels{t} = MarkTxt;
else
[CB.Ticks,ord] = sort([CB.Ticks value],'ascend');
t = CB.Ticks==value;
CB.TickLabels{t} = MarkTxt;
end
%% OR - in case you want the value to appear:
value = -1.24;
t = find(CB.Ticks==value);
if ~isempty(t)
CB.TickLabels{t} = [CB.TickLabels{t} MarkTxt];
else
[CB.Ticks,ord] = sort([CB.Ticks value],'ascend');
t = CB.Ticks==value;
CB.TickLabels{t} = [CB.TickLabels{t} MarkTxt];
end
Upvotes: 5
Reputation: 18197
You can simply add text
outside the plotting area and use that for your marker:
A = rand(15);
f=figure;
imagesc(A);
text(7,7,'X','Color','red') % Put a red X in the middle
text(17.5,size(A,1)*(1-A(7,7)),'<marker'); % Set a marker on the colour bar for the middle point
colorbar
Which results in:
I haven't found a way yet to plot a marker over the colour bar, as the colour bar is not one of the plot children which I can use in uistack
for some reason.
Upvotes: 2