开发者

annotation in matlab plot

开发者 https://www.devze.com 2022-12-26 09:07 出处:网络
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);

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 defi开发者_如何转开发ned 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?


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.


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);


I had some trouble understanding the normalized coordinates, until I realized that the coordinates (0,0) and (1,1) are respectively the lower left corner and upper right corner of the COMPLETE plot window, not just of the plot. The below snippet and the screenshot might help others who have been wondering where the 0 starts and the 1 ends.

x = -1:0.1:1;
y = x.^2;
plot (x,y)
xlabel('time [s]')
ylabel('amplitude')
title('My nice plot')
legend('y(t)')
grid on
annotation('arrow', [0 1], [0 1])

Plot with arrow coordinates (0,0) and (1,1)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号