version 4.1.1 (47.9 KB) by
Adam Danz

Automatically label points in your plot given x and y values & an array of labels.

**Editor's Note:** This file was selected as MATLAB Central Pick of the Week

[Major update with additional features coming soon; don't forget to follow this file.]

Given vectors of x-values, y-values, and a vector of label names, lablepoints.m will automatically place all labels appropriately in the plot and output their handles. This function streamlines matlab's builtin text() function and greatly increases its flexibility.

.

xpos = [1,2,3,4]; ypos = [1,4,1,5]; labels = {'Lancaster', 'Cincinnati', 'Sofia', 'Rochester'}

h = labelpoints (xpos, ypos, labels)

.

(optional) Choose where you want your label relative to the data point using initials of compass directions (N, S, E, W, NE, NW, SE, SW, Center).

h = labelpoints (xpos, ypos, labels, 'N')

.

(optional) Add (or subtract) extra space between data points and labels by using a buffer between 0:1

h = labelpoints (xpos, ypos, labels, 'N', 0.15)

.

(optional) Decide whether or not the axis limits should automatically adjust if a label falls out of the axis limits (0/1)

h = labelpoints (xpos, ypos, labels, 'N', 0.15, 1)

.

(optional) Let labelpoints.m identify and label only the outliers in your data. Several outlier methods are available (see help labelpoints)

- Identify and label outliers that are N standard deviations from the mean

- Identify and label outliers that are greater than N times the interquartile range

- Identify and label outliers that are inside or outside of a given bound

- Identify and label outliers that are high residuals from a linear fit of the data.

.

(optional) Easily place texts in a list stacked downward, upward, to the left or right.

h = labelpoints (xpos, ypos, labels, 'N, 'stacked', 'down')

.

(optional) Rotate all labels

h = labelpoints (xpos, ypos, labels, 'rotation', 45)

.

(optional) Specify the font size and color of all labels

h = labelpoints (xpos, ypos, labels, 'FontSize', 12, 'Color', 'r')

.

The help section includes many versatile examples demonstrating labeling with numbers, strings, and symbols. This function is quite flexible as the examples show. There are only three required inputs, 3 optional inputs, and several optional parameters to increase flexibility. The outlier options may require stats toolbox.

Adam Danz (2021). labelpoints (https://www.mathworks.com/matlabcentral/fileexchange/46891-labelpoints), MATLAB Central File Exchange. Retrieved .

Created with
R2016a

Compatible with any release

**Inspired by:**
vdpdemo

**Inspired:**
hist3d(x,y,w,varargin), Getting Started with Portfolio Optimization (Files for Video Demo)

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!Create scripts with code, output, and formatted text in a single executable document.

Ed RojasI was able to use the labelpoints function with Matlab's compose function to round the values to any number of decimal places before sending those values into labelpoints. The author, Adam Danz, provided me some useful hints. Thank you once more!

Adam DanzThanks for the feedback, Ed Rojas.

Ed RojasAwesome work. Your code was useful to label some data points on a loglog plot. I spent over two hours using the text function. Never worked. Thank you!

Soumyajit MandalNever mind, problem solved. Thanks

Soumyajit MandalRunning the basic example

xpos = [1,2,3,4]; ypos = [1,4,1,5]; labels = {'Lancaster', 'Cincinnati', 'Sofia', 'Rochester'}

h = labelpoints (xpos, ypos, labels)

Generates a blank plot. None of the other examples seem to work either. No error messages generated.

Testing on R2020b.

Adam Danz@Nik Rocky, I reached out to you via your community profile contact button. Please replay with the requested information if you'd like help solving this problem using labelpoints.

Nik RockyHello, I get error now (also with example code):

xpos = [1,2,3,4]; ypos = [1,4,1,5];

labels = {'Lancaster', 'Cincinnati', 'Sofia', 'Rochester'};

h = labelpoints (xpos, ypos, labels)

Error using axis (line 84)

x-axis and y-axis limits have different data types. Use xlim and ylim functions

instead.

Error in labelpoints/get_compass (line 456)

a = axis(axHand)/10;% I've somewhat arbitrarily divided by 10 to

make 'buffer' more sensitive

Error in labelpoints (line 434)

[va, ha, u1, u2] = get_compass(upper(p.Results.position), buf, bufferUnits);

Whyis ths happens? Earlyer it was working.

Manuel BrandnerLeslie HeidBN2Gabriel Hasmannxudong liuThanks very much ,

A dynamic economic model needs this function file.

Sincerely yours，

Daniel Tulips Liu

Marco PiantiniAdam DanzThanks, Brad! Still stress-testing the next update which contains some cool near features. To apply the same multi-line label to multiple areas of the plot, you've got two options shown below. If you have any other questions feel free to PM me (contact button in my profile). OPTION 1: Set up a multi-line char array. label = ['Line1',newline,'Line2',newline,'Line3']; labelpoints([.2,.4,.6],[.2,.4,.6], label); OPTION 2: Use a cell array to set the label strings. h = labelpoints([.2,.4,.6], [.2,.4,.6], '');

set(h,'String',{'Line1','Line2','Line3'});

Brad StiritzHi Adam, I'm still loving your function, it's so appreciated and useful to me :) Thank you very much again for your continued work on this outstanding utility.

I saw your dialog below on 13 Dec 2017, about multi-line labels. I need to render the same multi-line label at multiple locations in my chart. I was only able to get this to work via arrayfun(@(idx)labelpoints(X(idx),Y(idx),...),idx). Is there another approach that can work in a single call to labelpoints() ?

Best wishes and good luck with the major update. I'm looking forward to checking it out!

Mohamed BrahmiThank you very much! Works perfectly!

Nik RockyThank you very much!

How can I put values to foreground?

JoggerVery Nice and really useful

Aurea94Omar AqelAdam Danz@Aaron Mawby, use the "axHand" property to specify the axis handle. I will soon release an update where the axis handle is optionally specified by the 1st input. Example for now: ax = subplot(2,2,1); labelpoints(x,y,labels,'N','axHand', ax); You can also call labelpoints() after creating the subplot to use the current axes.

Aaron MawbyI can't seem to get this working with multiple subplots. It always wants to add the data labels to the last subplot regardless of which ax i have active.

Pierce Ivan Oliver Mistadesviyils SangregorioVery usefull

Wolfgang GaderbauerFlawless to use, well documented, great code! Thank you!

BN2Dear Adam Danz,

Thank you for creating this useful and awesome function.

SHIVANAND SamshetteJeff SeverinoGreat documentation! It could even be used as an example for writing good comments and help sections!

Alisa FinkbeinerEasy to use, thank you!

Trevor McSwainJacob WilliamsDan HallattAngelos KalitzeosAdam Danz@Eko Leksono, it works with pzmap(). Here's a demo (I'm using matlab 2018a).

H = tf([2 5 1],[1 3 5]);

pzmap(H)

grid on

hold on

plot(-1, 1, 'rx')

labelpoints(-1, 1, 'Here', 'NE', 'color', 'r')

Eko LeksonoI cannot use it in s-plane plot (pzmap) :(

Adam Danz@ed, thanks! Subscripts and superscripts are possible with labelpoints(); just follow the example below. I've been meaning to update the code so users can specify the interpreter property but here's a way to do it in the meantime.

figure; axes

h(1) = labelpoints(.2, .2, 'H_{2}O', 'center'); %subscript

h(2) = labelpoints(.4, .4, 'H^{2}O', 'center'); %superscript

set(h, 'Interpreter', 'tex')

edHi, great toolbox! For later versions it would be great to be able to use subscripts (and superscripts), for instance if points should be labeled by chemical elements.

minibelavery useful! thank you!

Karl BehrendtBrilliant, great time saver!

Udo SchröderIt would be great if you could extend the function to scatter3 plots.

Carrie SunDunno why this is rated anything less than 4 or 5. This is very straightforward and intuitive. Maybe this Eva needs to practice on basic Matlab before using this. Anyway, thank you for this!

Eva SkvorMithunThank you!

Gabriel NobertWorks very well. However, it would be interesting to make the extra space parameter work for logarithmic plots.

YANAN ZHUFabio GomezAdam DanzShane S, as for the outliers, you can get those from the boxplot output which outputs a bunch of handles used in the boxplot. Follow this example below (you may need to run it more than once in case no outliers are produced)

fakedata = normrnd(20, 50, 1, 400);

bh = boxplot(fakedata);

% find the handle that stores the outliers

hOutliers = findobj(bh,'Tag','Outliers');

% Use the handle to pull the (x,y) coordinates of the outliers

labelpoints(hOutliers.XData,hOutliers.YData, hOutliers.YData, 'E', 1,1, 'outliers_N', 10)

% give labelpoints 5 stars :D

ShaneSHow can label outliers on boxplot with this , please?

Andreas BThank you very much Adam, I very much appreciate it!

Adam Danz@Andreas, it's possible to do this by making the labels have multiple lines. Here's an example:

figure; plot([1 2 3],[1 2,3], 'o')

label = sprintf('Row 1\nRow 2'); %here, the \n means new row.

labelpoints(2,2, label, 'NE', 0.1)

Try is again with

label = sprintf('Row 1\nRow 2\nRow 3');

Andreas BThis gave me almost everything I needed in one function - thank you very mucht!

Just one more question for me: is it possible to stack multiple values on multiple markers? E.g., I got a marker (x,y), on which I want to show the numerical y-value and, say, the date when it was recorded in a second line. My workaround would be to call the function twice, first with the numerical value, say, to the north and then with the date to the south.

Ofir Shein LumbrosoReally great function, thanks!

Is there also a version compatible with the "App Designer"?

Kylie HansenDoes exactly what I needed. Thanks a lot!!!

Adam DanzThanks, Simon. Unfortunately the function only considers the x and y axes for now and plots everything on the z axis at z=0. Below is a snippet of code to show an example with a 3D plot. If you manually rotate the 3D plot you'll see that the labels are in the correct (x,y) coordinates and are at z=0. It wouldn't take a lot to add a z-axis functionality but I don't have time this week to dig into that.

figure('units','normalized','outerposition',[0 0 1 1])

[X,Y,Z] = sphere(16);

x = [0.5*X(:); 0.75*X(:); X(:)];

y = [0.5*Y(:); 0.75*Y(:); Y(:)];

z = [0.5*Z(:); 0.75*Z(:); Z(:)];

scatter3(x,y,z)

select = [200, 400, 600];

hold on;

scatter3(x(select),y(select),z(select), 'markerfacecolor', 'r')

labels = strsplit(sprintf('(%.2f, %.2f)|', reshape([x(select), y(select)]', [1,6])), '|');

labelpoints(x(select), y(select), labels(1:end-1), 'N', 'fontsize', 12)

xlabel('x axis')

ylabel('y axis')

Simon BouvotCool function, works fine with scatter function : thanks.

A question : How to have labels in 3D with scatter 3 ? Labels are in 2D I think.

Thanks €.

Chang hsiungperfect works, thanks a lot

Adam DanzHi Brad, the function has been updated to accept datetime label positions. Let me know if there are any problems since I haven't use this func much with datetime data. However, I did test it with the following code.

t = datetime(2014,6,28) + calweeks(0:9);

y = rand(1,10);

plot(t,y);

labelpoints([datetime(2014,7,12), datetime(2014,8,24)], [0.4, 0.6], 'here->', 'W')

Brad StiritzHi Adam, thanks for your great work on this. I would like to use your function to annotate time series plots, where the X-values are datetime (introduced in R2014b). Your function doesn't seem to support this directly:

>> labelpoints(my_datetimes,Y_values,char(my_datetimes),'S')

Error using labelpoints (line 258)

Comparison is not defined between datetime and double arrays.

I tried a few different hacks, with no success. For example:

>> labelpoints(datenum(my_datetimes),Y_values,char(my_datetimes),'S')

Error using axis (line 80)

x-axis and y-axis limits have different data types. Use xlim and ylim functions

instead.

Error in labelpoints (line 296)

a = axis/10;% I've somewhat arbitrarily divided by 10 to make 'buffer' more

sensitive

Changqing LuThanks so much!

Gizem OkyaySeunghak LeeThis is great!! Thank you!

pradeep kumarThank You Very much! It perfectly works for me.

Chenfei YeThank you for your contribution. It works well

Ivan AbrahamChatarin WangsanuwatAdam DanzEasy. Here's a demo:

%Fake Data

x = rand(1,10);

y = rand(1,10);

labels = rand(1,10)*10;

% add string to values

strLabels = sprintf('w=%.1f|', labels);

strLabels(end) = []; %remove final separater

%split long string into cell array

cellLabels = strsplit(strLabels, '|');

%plot and labelpoints

plot(x,y, 'o')

labelpoints(x,y,cellLabels,'NE')

Issa AsrawiI need to add w = ... at each point in my graph. Any help please?

Hyeyun YangLiutongexcellent!

Craig ColeGordonWorks for my problem. Thank you!

BarisA NMarcelo Birche FerriVery nice and helpfull tool, thx!

Ryan RichardsonVery good tool. Would like to be able to select only certain strings to add as labels

Warwickvery good, easy to use.

Brad StiritzVery helpful, thank you!

I appreciate being able to select single labels after rendering, and reposition manually. Scatter points can be very close sometimes, leading to overlapping.

Highly recommended.

Zhan Yang Limfound it

luca de vivojvcFabulous! Thanks very much for this very useful tool.

William PersampieriVery easy to drop into my code - took me 60sec to add data labels to my figure! Thanks Adam!

cmoAnnickAmazing!! Thanks for this.

Adam DanzSoon I will update this file with a new version that has the option of labeling only the outliers which will be calculated within the function. Check back in a couple of weeks if interested. (3-Nov-2014)

Adam DanzJust to follow up, the subplot issue mentioned previously has been resolved and was not a problem with labelpoint.m

This function works well with subplots, too.

LeyonVery useful. Thanks.

Have a problem using with subplot. Even with the use of the extra option its placement of labels is crazy.

Was using it with a (4,2,s) subplot of bar graphs to plot frequencies and label with probabilities.

Any help to fix the issue would be nice