今天我们要学习,如何在figure中添加注释, 并指向方向。
首先画出数据,并添加一条均值线
Line([mean1 mean1], get(gca,’ylim’));
如图:
添加文本连接指向均值线,使用dsxy2figxy从数据空间转换点或位置坐标进入标准的图坐标中,annotation添加图像的注释文本,即指向均值线
function varargout = dsxy2figxy(varargin)
if length(varargin{1}) == 1 && ishandle(varargin{1}) ...
&& strcmp(get(varargin{1},'type'),'axes')
hAx = varargin{1};
varargin = varargin(2:end); % Remove arg 1 (axes handle)
else
hAx = gca;
end;
% Remaining args are either two point locations or a position vector
if length(varargin) == 1 % Assume a 4-element position vector
pos = varargin{1};
else
[x,y] = deal(varargin{:}); % Assume two pairs (start, end points)
end
% Get limits
axun = get(hAx,'Units');
set(hAx,'Units','normalized'); % Make axes units normalized
axpos = get(hAx,'Position'); % Get axes position
axlim = axis(hAx); % Get the axis limits [xlim ylim (zlim)]
axwidth = diff(axlim(1:2));
axheight = diff(axlim(3:4));
% Transform from data space coordinates to normalized figure coordinates
if exist('x','var') % Transform a and return pair of points
varargout{1} = (x - axlim(1)) * axpos(3) / axwidth + axpos(1);
varargout{2} = (y - axlim(3)) * axpos(4) / axheight + axpos(2);
else % Transform and return a position rectangle
pos(1) = (pos(1) - axlim(1)) / axwidth * axpos(3) + axpos(1);
pos(2) = (pos(2) - axlim(3)) / axheight * axpos(4) + axpos(2);
pos(3) = pos(3) * axpos(3) / axwidth;
pos(4) = pos(4) * axpos(4 )/ axheight;
varargout{1} = pos;
end
% Restore axes units
set(hAx,'Units',axun)
完整代码:
plot(x,y1);
%% Add the |line| at the mean position
line([mean1 mean1],get(gca,'ylim'));
%% Add the |text arrow| annotation, working from data space annotation
% Convert to norm fig units
[xmeannfu ymeannfu]= dsxy2figxy(gca,[.5,0],[.15,.05]);
% Add the annotation component
annotation('textarrow',xmeannfu,ymeannfu,'String','Mean');
title({'The standard normal probability distribution',...
' function is plotted with the mean pointed out with', ...
'a text arrow to make the figure more informative'});
xlabel('x');ylabel('probability of x');
set(gcf,'Paperpositionmode','auto','Color',[1 1 1]);
结果图: