一、概述
在 Matlab 中繪製圖形時,有時需要在一張圖上同時繪製多個函數曲線。此時,我們可以使用 hold on 和 hold off 指令來控制 Matlab 圖像窗口中的圖形繪製。
二、hold on 和 hold off 的基礎語法
hold on和hold off 指令可用來控制曲線的重疊,以便在同一個坐標系下同時繪製多個曲線。
% 比如繪製sin和cos函數 x = 0:0.1:pi; y1 = sin(x); y2 = cos(x); % hold on 命令 plot(x,y1); hold on; plot(x,y2); hold off;%使用 hold off 恢復正常繪圖狀態
上述代碼中,hold on 命令會啟用 Matlab 圖像窗口的隱藏功能,以允許用戶在同一張圖中繪製多張圖,並且 hold off 命令會將窗口繪圖設置為正常狀態,以便用戶可以在此後的圖形中繪製單個線條。
三、hold 的其他參數
因為在控制曲線繪製時,使用 hold on 和 hold off 命令會改變圖形對象的狀態,所以在繪製圖形時,有些用戶不會使用 hold off 命令。但是,為保證圖形對象的狀態不會進一步改變,也可以使用其他 hold 命令參數。
例如:當把 nextplot 屬性設置為 add 時,圖形中的所有任何繪圖都將覆蓋到前一個繪圖上,從而創建多重圖層效果。
x = [0:pi/100:2*pi]; y1 = sin(x); y2 = cos(x); plot(x,y1); set(gca,'nextplot','add') plot(x,y2) set(gca,'nextplot','replace')
上述例子中,使用 set 命令設置 nextplot 屬性,將「add」作為其參數輸入,這樣會持續使用 hold on 的功能在圖像窗口畫布上繪製圖表。
四、hold 區分 Figure 和 Axes 句柄
注意:hold 命令會應用於畫圖區域的 Figure 和 Axes 對象。雖然在許多情況下, Figure 和 Axes 對象是相同(只有一個 Axes 子對象)的,但在其他情況下,它們是不同的。
如果指定 Axes 對象的父級 Figure 對象在 hold 狀態下被保存,那麼後續的 Plot 函數可以通過新 Axes 對象使用 hold 命令,從而影響 Figure 對象的現有 Axes 對象。此時,如果您想讓某個圖表返回到非 hold 狀態,請重置該圖表的 Axes 對象。
注意,此時 reset 所有的 Axes,而不僅僅是當前 Axes 對象。
% 一個清空reset的例子 x = [0:pi/100:2*pi]; y1 = sin(x); y2 = cos(x); figure; plot(x,y1); set(gca,'nextplot','add') plot(x,y2) figure; plot(x,y1); set(gca,'nextplot','add') plot(x,y2) hold on; plot(x,cos(x),'r--') hold off; % Create a new figure figure; plot(x,y1); % This axes is the current axes, which means the next plot command will % write on it unless hold is active hold on; plot(x,cos(x),'r--') hold(gca,'on') % This plot will write on the same axes plot(x,cos(x).^2,'g:') hold off;
五、優化曲線的性能和外觀
hold 命令可用於優化曲線的性能和外觀,例如在多次更新曲線時凍結 Y 軸限制,以避免自動縮放,從而產生可見的閃爍。
% 追蹤 sine 函數的振幅與相位 ax = gca; hold(ax,'on') for k = 1:50 y = sin(k*x + rand*pi/2); plot(ax,x,y,'k','LineWidth',1.5) ax.YLim = [min(y) max(y)]; pause(0.1) end hold(ax,'off')
六、小結
在 Matlab 中,hold on 和 hold off 命令可用於控制曲線的繪製。在使用這些命令時,請始終注意是否需要設置 Figure 和 Axes 對象的狀態。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/154444.html