Files
Paper.Formatting.Guidelines/scripts/matlab/arrow.m
T
2024-12-05 17:41:01 +08:00

73 lines
3.1 KiB
Matlab

function hAnnot = arrow(startPoint, endPoint, ax, arrowType, varargin)
% ARROW Draws an annotation of specified type between two data points.
%
% hAnnot = ARROW(startPoint, endPoint, ax, arrowType) creates an
% annotation from the coordinate specified by startPoint to the coordinate
% specified by endPoint. The annotation type can be 'arrow', 'doublearrow',
% 'textarrow', etc.
%
% hAnnot = ARROW(startPoint, endPoint, ax, arrowType, Name, Value) allows
% additional customization of the annotation properties (e.g., color,
% arrowhead size, line width, etc.).
%
% INPUT:
% startPoint - 1x2 array, [x1, y1], coordinates of the start point
% in the data space of the current axes.
% endPoint - 1x2 array, [x2, y2], coordinates of the end point
% in the data space of the current axes.
% ax - (optional) Axes handle. If omitted, the current axes
% (gca) will be used.
% arrowType - (optional) Type of annotation ('arrow', 'doublearrow',
% 'textarrow', etc.). Default is 'arrow'.
% Name, Value - (optional) Name-value pairs to customize the annotation's
% appearance (e.g., 'Color', 'LineWidth', etc.).
%
% OUTPUT:
% hAnnot - Handle to the created annotation object.
%
% Example:
% figure;
% x = linspace(0, 10, 100);
% y = sin(x);
% plot(x, y);
% arrow([2, sin(2)], [8, sin(8)], gca, 'textarrow', 'Color', 'r', 'String', 'Text');
%
% Notes:
% The function automatically converts the data coordinates to normalized
% figure coordinates for annotation purposes.
% Input validation
if nargin < 2
error('arrow:InsufficientInputs', 'Both startPoint and endPoint must be specified.');
end
if nargin < 3 || isempty(ax)
ax = gca; % If axes handle is not provided, use the current axes
end
if nargin < 4 || isempty(arrowType)
arrowType = 'arrow'; % Default arrow type is 'arrow'
end
if numel(startPoint) ~= 2 || numel(endPoint) ~= 2
error('arrow:InvalidInput', 'startPoint and endPoint must be 1x2 arrays representing [x, y] coordinates.');
end
% Get the current axes position in normalized figure units
ax_pos = ax.Position;
% Convert data coordinates to normalized figure coordinates
startNorm = [(startPoint(1) - ax.XLim(1)) / diff(ax.XLim), ...
(startPoint(2) - ax.YLim(1)) / diff(ax.YLim)];
endNorm = [(endPoint(1) - ax.XLim(1)) / diff(ax.XLim), ...
(endPoint(2) - ax.YLim(1)) / diff(ax.YLim)];
% Map normalized data coordinates to figure normalized coordinates
startAnnot = [ax_pos(1) + startNorm(1) * ax_pos(3), ...
ax_pos(2) + startNorm(2) * ax_pos(4)];
endAnnot = [ax_pos(1) + endNorm(1) * ax_pos(3), ...
ax_pos(2) + endNorm(2) * ax_pos(4)];
% Create the specified type of annotation
hAnnot = annotation(arrowType, [startAnnot(1) endAnnot(1)], ...
[startAnnot(2) endAnnot(2)], ...
varargin{:}); % Pass additional name-value pairs
end