MATLAB: Does the HOLD ON command not work when I try to update figures with subplots

holdMATLABnextplotsubplot

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))

Best Answer

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