Matlab can gca and gcf replaced?
67 次查看(过去 30 天)
显示 更早的评论
Hello I wonder how to refer to particular figure and/or axes when I do not use gca or gcf right after plot and figure commands. I think these things get a lot more complex in subplots. Is there a way to obtain the axes of a plot without issuing these two commands? Are there good tutorials on these on the web?
0 个评论
回答(2 个)
Stephen23
2016-8-22
编辑:Stephen23
2016-8-22
The simplest way is to read the documentation, and you will find that every graphics function returns the handles of the graphics objects that it creates. The plotting functions also accept an axes handle, so you can specify exactly which axes to plot in:
fgh = figure(...)
axh = axes(fgh,...)
lnh = plot(axh,...)
Never rely on gca, gcf or anything similar: they are unreliable and will make your code buggy because their behavior depends on what the user clicked on, or what code has just run... basically using gcf and gca is how beginners write buggy, unreliable code. They should be used for playing in the command window, not for any serious code.
8 个评论
Steven Lord
2021-3-19
You're assuming the user didn't click on a different figure (making it active) between the creation of the plots in one figure and the call to gcf. The current figure may not be the one you expect to be current.
Walter Roberson
2021-3-19
Also, anything like msgbox() or menu() or questdlg() creates a new figure. uigetfile() has unspecified implementation that is permitted to create a new figure (whether it does or not can depend on the operating system)
Star Strider
2016-8-22
It’s not necessary to use gca and gcf for the axis and figure handles if you return the handle from the particular command.
Example:
Fig1 = figure(1);
ax211 = subplot(2,1,1);
plot([1:10], [1:10]+randn(1,10)*0.1, 'bp')
grid
subplot(2,1,2)
sp212 = plot([1:10], sin([0:9]*2*pi/9));
grid
Fig1Pos = Fig1.Position; % Figure 1 Position
xt211 = ax211.XTick; % Get X-Tick Values For Subplot 2,1,1
Ydata212 = get(sp212,'Ydata'); % Get Y-Data For Subplot 2,1,2
0 个评论
另请参阅
类别
在 Help Center 和 File Exchange 中查找有关 Graphics Object Properties 的更多信息
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!