File Exchange

image thumbnail

labelpoints

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.

133 Downloads

Updated 26 Jan 2020

View Version History

View License

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.

Cite As

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

Comments and Ratings (74)

Marco Piantini

Adam Danz

Thanks, 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 Stiritz

Hi 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 Brahmi

Thank you very much! Works perfectly!

Nik Rocky

Thank you very much!

How can I put values to foreground?

Matlab

Very Nice and really useful

Aurea94

Omar Aqel

Adam 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 Mawby

I 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.

viyils Sangregorio

Very usefull

Wolfgang Gaderbauer

Flawless to use, well documented, great code! Thank you!

Behzad Navidi

Dear Adam Danz,
Thank you for creating this useful and awesome function.

SHIVANAND Samshette

Jeff Severino

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

Alisa Finkbeiner

Easy to use, thank you!

Trevor McSwain

Jacob Williams

Dan Hallatt

Angelos Kalitzeos

Adam 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 Leksono

I 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')

ed

Hi, 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.

minibela

very useful! thank you!

Karl Behrendt

Brilliant, great time saver!

Udo Schröder

It would be great if you could extend the function to scatter3 plots.

Carrie Sun

Dunno 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 Skvor

Mithun

Thank you!

Gabriel Nobert

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

YANAN ZHU

Fabio Gomez

Adam Danz

Shane 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

ShaneS

How can label outliers on boxplot with this , please?

Andreas B

Thank 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 B

This 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 Lumbroso

Really great function, thanks!
Is there also a version compatible with the "App Designer"?

Kylie Hansen

Does exactly what I needed. Thanks a lot!!!

Adam Danz

Thanks, 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 Bouvot

Cool 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 hsiung

perfect works, thanks a lot

Adam Danz

Hi 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 Stiritz

Hi 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 Lu

Thanks so much!

Gizem Okyay

Seunghak Lee

This is great!! Thank you!

pradeep kumar

Thank You Very much! It perfectly works for me.

Chenfei Ye

Thank you for your contribution. It works well

Ivan Abraham

Chatarin Wangsanuwat

Adam Danz

Easy. 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 Asrawi

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

Hyeyun Yang

Liutong

excellent!

Craig Cole

Gordon

Works for my problem. Thank you!

Baris

A N

Marcelo Birche Ferri

Very nice and helpfull tool, thx!

Ryan Richardson

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

Warwick

very good, easy to use.

Brad Stiritz

Very 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 Lim

found it

luca de vivo

jvc

Fabulous! Thanks very much for this very useful tool.

William Persampieri

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

cmo

Annick

Amazing!! Thanks for this.

Adam Danz

Soon 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 Danz

Just 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.

Leyon

Very 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

MATLAB Release Compatibility
Created with R2016a
Compatible with any release
Platform Compatibility
Windows macOS Linux

Community Treasure Hunt

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

Start Hunting!