Refresh overlaid plots without "hold on/hold off" in each loop iteration
13 views (last 30 days)
Show older comments
Aswathylakshmi
on 14 Mar 2025
Commented: Aswathylakshmi
on 14 Mar 2025
I have a script with multiple figures that are updated in a for loop using their figure and axes handles. One of the figures is a pair of scatterplots overlaid on each other. I need both these concurrent scatterplots cleared at the beginning of each iteration, before updating with the new data for both of them. When using the "hold on" command to overlay the scatterplots on a single figure, I am unable to clear the second one for the next loop iteration using the "set" command. Here's a snippet of my code:
for i = 1 to N
% Figure 1 (with overlaid scatterplots)
if ~(exist(fig1))
fig1 = figure;
f1 = subplot(2,1,1,'Parent',fig1);
%% Overlay 2 scatterplots in this subplot %%
sc1 = scatter(x1,y1,'b','Parent',f1);
hold on;
scatter(x2,y2,'r','Parent',f1);
% Other subplots %
else
figure(fig1)
% Update new info for both scatterplots and overlay them in the first subplot
set(sc1,'XData',x1,'YData',y1,'CData',repmat(sc1.CData(1,:)),'Parent',f1);
hold on;
scatter(x2,y2,'r','Parent',f1);
% Other subplots %
end
% Plot some other figure
if ~(exist(fig2))
fig2 = figure;
ax = axes('Parent',fig1);
% Plot Figure 2
else
figure(fig2)
% Figure 2 plots and legends using ax
end
end
The problem is, the second scatterplot does not get cleared in the next loop iteration when set(sc1,...) is called. I tried the cla(f1,'reset') command, but that deletes all the XData, YData variables, which I need to exist in order to update.
I think the "hold on" is creating the persistence issue, but adding "hold off" after the second scatter just clears the entire subfigure including axes.
Is there some other way to accomplish the goal of overlaid scatterplots refreshed in each loop?
0 Comments
Accepted Answer
Image Analyst
on 14 Mar 2025
To clear the second set of markers, get a handle to them and call delete
sc2 = scatter(x2,y2,'r','Parent',f1); % Create markers
delete(sc2); % Call this to delete them when you want them to disappear.
More Answers (0)
See Also
Categories
Find more on Annotations in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!