MATLAB画矢量箭头图(含MATLAB代码)

一、代码

主函数:main.m

close all
clear; clc;
x = 0:0.2:4*pi;
y = sin(x);
plot(x, y, '.');
hold on
all_colors1=[0.2 0.9 0.3];%点的颜色
all_colors2=[0.8 0.2 0.4];%线的颜色
for i = 1:length(x)-1
    PlotLineArrow(gca, [x(i), x(i + 1)], [y(i), y(i + 1)], all_colors1, ...
        all_colors2, 1);
end
hold off
xlabel('x')
ylabel('sin(x)')

画图函数:PlotLineArrow.m

function PlotLineArrow(obj, x, y, markerColor, lineColor, lineWidth)
% 绘制散点图
plot(x, y, 'o', 'Color', markerColor, 'MarkerFaceColor', markerColor);
% 获取 Axes 位置
posAxes = get(obj, 'Position');
posX = posAxes(1);
posY = posAxes(2);
width = posAxes(3);
height = posAxes(4);
% 获取 Axes 范围
limX = get(obj, 'Xlim');
limY = get(obj, 'Ylim');
minX = limX(1);
maxX = limX(2);
minY = limY(1);
maxY = limY(2);
% 转换坐标
xNew = posX + (x - minX) / (maxX - minX) * width;
yNew = posY + (y - minY) / (maxY - minY) * height;
% 画箭头
annotation('arrow', xNew, yNew, 'color', lineColor, 'LineWidth', lineWidth);
end

二、效果

MATLAB画矢量箭头图(含MATLAB代码)_第1张图片
参考:https://zhuanlan.zhihu.com/p/127356584

你可能感兴趣的:(MATLAB,IT技术,matlab)