views:

334

answers:

2

Hi,

I just wonder how to add annotation in matlab plot? Here is my code:

plot(x,y);  
annotation('textarrow',[x, x+0.05],[y,y+0.05],'String','my point','FontSize',14);

But the arrow points to the wrong place. How can I fix it? And any better idea for annotating a plot?

Thanks and regards!


EDIT:

I just saw from the help document:

annotation('line',x,y) creates a line annotation object that extends from the point defined by x(1),y(1) to the point defined by x(2),y(2), specified in normalized figure units.

In my code, I would like the arrow pointing to the point (x,y) that is drawn by plot(), but annotation interprets the values of x and y as in normalized figure units. So I think that is what causes the problem. How can I specify the correct coordinates to annotation?

+3  A: 

First, you need to find the position of the axes in normalized figure units. Fortunately, they're set to 'normalized' by default.

axPos = get(gca,'Position'); %# gca gets the handle to the current axes

axPos is [xMin,yMin,xExtent,yExtent]

Then, you get the limits, i.e. min and max of the axes.

xMinMax = xlim;
yMinMax = ylim;

Finally, you can calculate the annotation x and y from the plot x and y.

xAnnotation = axPos(1) + ((xPlot - xMinMax(1))/(xMinMax(2)-xMinMax(1))) * axPos(3);
yAnnotation = axPos(2) + ((yPlot - yMinMax(1))/(yMinMax(2)-yMinMax(1))) * axPos(4);

Use xAnnotation and yAnnotation as x and y coordinates for your annotation.

Jonas
I claim that `xMinMax(2)` should actually be `(xMinMax(2)-xMinMax(1))`, similarly for `yMinMax(2)`.
Artelius
@Artelius: good catch!
Jonas
A: 

Another way to get normalized figure coordinates is to use Data space to figure units conversion (ds2nfu) submission on FileExchange.

[xa ya] = ds2nfu(x,y);
yuk