一种方法是使用annotations,但有一些缺点(见下文)。
注释使您能够将各种图形对象放入图形中。关于它们的一件非常烦人的事情是它们在所谓的规范化坐标中工作,
它跨越整个图形窗口(不仅仅是绘图区域)并从 [0,0] 到 [1,1],迫使您首先转换为这些坐标。我写了一个简单的函数来做到这一点,前提是你的绘图比例是线性的(如果你想要对数,你必须修改这个函数):
## Convert from data coordinates to normalized figure coordinates.
function [xf yf] = figcoords(xa, ya)
axp = get(gca, "position");
lf = axp(1);
bf = axp(2);
rf = lf + axp(3);
tf = bf + axp(4);
xl = xlim();
yl = ylim();
la = xl(1);
ra = xl(2);
ba = yl(1);
ta = yl(2);
xf = lf + (xa-la).*(rf-lf)./(ra-la);
yf = bf + (ya-ba).*(tf-bf)./(ta-ba);
endfunction
解决了这个问题,您可以继续使用annotation 函数对绘图进行注释:
y = [0.1 0.3 10.0 1.0 0.5 0.1 24.0 0.6 0.1 0.2];
x = (1:length(y));
peaks = [3 7];
## Plot the data as you would normally
plot(x,y);
## Plot peak markers (no `hold on` needed)
[xp yp] = figcoords(peaks, y(peaks)); # Transform to figure coordinates
for coords = [xp; yp]
xpi = coords(1);
ypi = coords(2);
annotation("arrow", [xpi xpi], [ypi+eps ypi]);
endfor
Plot with annotated peaks
在这里,我们实际上绘制了从顶部指向山峰的小箭头。
由于它们的高度非常小,我们只能看到箭头。
annotation 函数的参数是 x 和 y 坐标
箭头的端点。请注意,我们添加了一个小数字 (eps)
到起点的 y 值,使箭头指向下方。
如果需要,您可以调整标记的外观,使其更具视觉吸引力:
y = [0.1 0.3 10.0 1.0 0.5 0.1 24.0 0.6 0.1 0.2];
x = (1:length(y));
peaks = [3 7];
coloridx = get(gca, "ColorOrderIndex")
peakcolor = get(gca, "ColorOrder")(coloridx,:); # Save current plot colour
plot(x,y);
## Plot peak markers
[xp yp] = figcoords(peaks, y(peaks));
for coords = [xp; yp]
xpi = coords(1);
ypi = coords(2);
annotation("arrow", [xpi xpi], [ypi+eps ypi], "headstyle", "plain",...
"color", peakcolor);
endfor
Plot with annotated peaks in the same color
缺点
尽管无论标记或绘图的大小如何,这种方法都可以正常工作,但也有一些缺点:
- 首先,注释相对于图形窗口 是固定的,而不是绘图。
当您第一次显示绘图时这很好,但是一旦您缩放
或平移,对齐丢失:当情节移动时,标记保持在原位。
如果您不需要交互式绘图(例如,您只想将其导出为图像),
只需确保在添加注释之前设置绘图限制,您应该
没事。
- 其次,与使用
plot 函数。例如,在我的电脑上,当用
七个带注释的峰,在标记出现之前大约需要一秒钟。
绘制具有数千个峰值的信号几乎是不可能的。