Why does the HOLD ON command not work when I try to update figures with subplots?

125 次查看(过去 30 天)
I have subplots in my figure. I execute HOLD ON before making changes to the subplots, however the plot on one of the axes gets removed when I make changes. As an example consider the following code:
figure(1),
h1 = subplot(1,2,1),line
h2 = subplot(1,2,2),line
hold on
figure(1)
axes(h1),plot(sin(0:1))
axes(h2),plot(sin(0:1))
% subplot(1,2,1),plot(sin(0:1))
% subplot(1,2,2),plot(sin(0:1))

采纳的回答

MathWorks Support Team
SUBPLOT clears the axes when called unless the new subplot properties (such as 'position') match the original subplot properties. There are two possible approaches one can take to work around this issue:
1) Use get(gcf,'Children') to obtain the handle to a particular plot (in this example, the leftmost plot).
close all;
clear all;
open test.fig;
%%Obtain handles to all subplots in current figure
h = get(gcf,'Children');
%%Extract subplot position information
for i = 1:3
positions(i,:) = get(h(i),'position'); % extract positions of each subplot
xpositions(i) = positions(i,1);
end
%%Find index of leftmost subplot
[xposition_min leftmost_index] = min(xpositions);
%%Set 'NextPlot' property of leftmost plot to 'add' (analogous to HOLD ON)
set(h(leftmost_index),'NextPlot','add');
%%Plot new data
plot(h(leftmost_index), [30 31 32],[15 20 25], 'bo');
2) When creating future subplots, set the 'Tag' property of the subplot to a memorable name and search for the tag when needed.
%%Create 3 subplots with tags
clear all; clf; clc;
h = subplot(1,3,1);
plot(sin(0:0.1:10));
set(h,'Tag','left');
h = subplot(1,3,2);
plot(tan(0:0.1:10));
set(h,'Tag','center');
h = subplot(1,3,3);
plot(sec(0:0.1:10));
set(h,'Tag','right');
%%Add new data to leftmost plot
h = findobj('Tag','left'); % get handle to object tagged as 'left'
set(h,'NextPlot','add'); % set 'NextPlot' property to 'add'
plot(h, cos(0:0.1:10),'r--'); % plot new data

更多回答(1 个)

Helen Zhu
Helen Zhu 2019-6-13
It seems like there are still many viewers of this page in year 2019. So I am providing another option: hold (ax, 'on')

产品


版本

R14SP1

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by