Label Maximum and Minimum in MatLab Figure


Sometimes it is required to label the minimum and maximum values of a plot in a Matlab figure. The code snippet below demonstrate that functionality, for minimum and maximum values along the y-axis.plot_label_min_max

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
% plot the data
data= [2.5 : 0.025 : 10];    	 		% x-axis data
fn1 = log(data.^2)./data + 0.035*data;	% y-axis data
h   = plot(data,fn1);                	% get handle for the plot
 
% label max and min values of a 'fn1' on the plot
xValue = get(h,'XData');
yValue = get(h,'YData');
imin = find(min(yValue)==yValue);% find the index for the min and max
imax = find(max(yValue)==yValue);% values of yValue
% label the max. and min. values  on the plot
text(xValue(imax),yValue(imax),['max.=',num2str(yValue(imax))],...
'VerticalAlignment','bottom','HorizontalAlignment',...
'left','FontSize',14);
text(xValue(imin),yValue(imin),['min.=',num2str(yValue(imin))],...
'VerticalAlignment','bottom','HorizontalAlignment',...
'right','FontSize',14);

If you want xValue corresponding to max(yValue), then change num2str(yValue(imax)) to num2str(xValue(imax)) on Line-12. Similarly edit the code for minimum value on Line-15

Leave a Comment