MATLAB如何让坐标轴带箭头 | 您所在的位置:网站首页 › matlab画坐标轴在原点 › MATLAB如何让坐标轴带箭头 |
文章目录
前言1 原始波形2 添加箭头3 设置回调函数总结附录参考资料
前言
本文主要介绍了如何给图添加坐标系,以正弦信号为例展示最终的效果,完整代码见附录。 1 原始波形首先生成正弦信号,代码如下: clc;clear;close all; t = -pi:0.01:pi; y = sin(t); plot(t,y) 运行结果: 代码如下1: set(gca,'box', 'off') % 去掉坐标区的框轮廓 set(gca,'XAxisLocation', 'origin'); % 设置x轴位置,使其穿过原点 set(gca,'YAxisLocation', 'origin'); % 设置y轴位置,使其穿过原点 pos = get(gca,'Position'); % 获取内坐标区的大小和位置 xL = xlim; % 获x取坐标轴范围 yL = ylim; % 获y取坐标轴范围 ax=gca; % 获取图窗句柄 % 横轴 dan1 = (yL(2)-yL(1))/pos(4); % 单位1代表的长度 pt1 = yL(1)-dan1*pos(2); % 内坐标区相对于下边界多出的部分 ax.UserData.AW{1} = annotation('arrow'); % 创建箭头对象,并将其保存在用户数据中 ax.UserData.AW{1}.X=[pos(1) pos(1)+pos(3)]; ax.UserData.AW{1}.Y=[(0-pt1)/dan1 (0-pt1)/dan1]; % 纵轴 dan2 = (xL(2)-xL(1))/pos(3); % 单位1代表的长度 pt2 = xL(1)-dan2*pos(1); % 内坐标区相对于左边界多出的部分 ax.UserData.AW{2} = annotation('arrow'); % 创建箭头对象,并将其保存在用户数据中 ax.UserData.AW{2}.X = [(0-pt2)/dan2 (0-pt2)/dan2]; ax.UserData.AW{2}.Y = [pos(2) pos(2)+pos(4)];运行结果: 图2的效果还不错,但是当拖动图片时,箭头会与坐标轴分离,如图3所示,这不是我们想看到的结果。 为了解决该问题,我们写一个回调函数,使箭头跟随鼠标的拖动而改变位置2。 % 回调函数 function MovAW(~,~)有了回调函数,只需在上述代码的基础上加上一行代码,即可实现我们想要的结果,即 MovAW() 拖动图形后的效果如图4所示。 以上简单实现了给图形添加坐标轴的操作,简单易行,代码中给出了详细的注释,易于理解。 附录主程序: t = -pi:0.01:pi; y = sin(t); plot(t,y) set(gca,'box', 'off') % 去掉坐标区的框轮廓 set(gca,'XAxisLocation', 'origin'); % 设置x轴位置,使其穿过原点 set(gca,'YAxisLocation', 'origin'); % 设置y轴位置,使其穿过原点 pos = get(gca,'Position'); % 获取内坐标区的大小和位置 xL = xlim; % 获x取坐标轴范围 yL = ylim; % 获y取坐标轴范围 ax=gca; % 获取图窗句柄 % 横轴 dan1 = (yL(2)-yL(1))/pos(4); % 单位1代表的长度 pt1 = yL(1)-dan1*pos(2); % 内坐标区相对于下边界多出的部分 ax.UserData.AW{1} = annotation('arrow'); % 创建箭头对象,并将其保存在用户数据中 ax.UserData.AW{1}.X=[pos(1) pos(1)+pos(3)]; ax.UserData.AW{1}.Y=[(0-pt1)/dan1 (0-pt1)/dan1]; % 纵轴 dan2 = (xL(2)-xL(1))/pos(3); % 单位1代表的长度 pt2 = xL(1)-dan2*pos(1); % 内坐标区相对于左边界多出的部分 ax.UserData.AW{2} = annotation('arrow'); % 创建箭头对象,并将其保存在用户数据中 ax.UserData.AW{2}.X = [(0-pt2)/dan2 (0-pt2)/dan2]; ax.UserData.AW{2}.Y = [pos(2) pos(2)+pos(4)]; MovAW() % 让箭头随着鼠标的拖动而改变MovAW.m function MovAW(~,~) cp_gca=gca; pos=cp_gca.Position; % 内坐标区的边界 yL = cp_gca.YLim; xL = cp_gca.XLim; % 横轴 dan1 = (yL(2)-yL(1))/pos(4); % 单位1代表的长度 pt1 = yL(1)-dan1*pos(2); % 内坐标区相对于下边界多出的部分 cp_gca.UserData.AW{1}.X=[pos(1) pos(1)+pos(3)]; cp_gca.UserData.AW{1}.Y=[(0-pt1)/dan1 (0-pt1)/dan1]; % 纵轴 dan2 = (xL(2)-xL(1))/pos(3); % 单位1代表的长度 pt2 = xL(1)-dan2*pos(1); % plot相对于下边界多出的部分 cp_gca.UserData.AW{2}.X = [(0-pt2)/dan2 (0-pt2)/dan2]; cp_gca.UserData.AW{2}.Y = [pos(2) pos(2)+pos(4)]; set(cp_gca.Parent,'WindowButtonMotionFcn',@MovAW); % 设置回调函数,当鼠标按下时执行该函数 end 参考资料坐标轴横纵坐标末如何画箭头 – MATLAB中文论坛 (ilovematlab.cn). ↩︎ MATLAB | 一行代码生成箭头坐标轴,为坐标轴增添箭头_slandarer的博客-CSDN博客_matlab坐标轴箭头. ↩︎ |
CopyRight 2018-2019 实验室设备网 版权所有 |