Reputation: 3200
Is it possible to replot a line after it has been deleted, using properties previously retrieved by 'get()'.
For example:
% Create the plot and 'get' its properties.
axes
P = plot(1:360, sind(1:360));
PG = get(P);
% Delete the plot.
delete(P)
% Replot the line...
plot(PG) % ?????
I'd like it to be generalizable, i.e. the solution would work for surface plots, line plots, text annotations, etc.
Upvotes: 3
Views: 496
Reputation: 112659
Instead of deleting and recreating the object, you could make it invisible:
set(P, 'visible', 'off')
and then visible again
set(P, 'visible', 'on')
If you really want to recreate a deleted object, you can proceed as follows: create an object of the same type and use a for
loop to set its properties to the stored values. A try
-catch
block is needed because some properties are read-only and issue an error.
%// Replot the object...
Q = plot(NaN); %// create object. Plot any value
fields = fieldnames(PG);
for n = 1:numel(fields)
try
set(Q, fields{n}, getfield(PG, fields{n})); %// set field
catch
end
end
You can use this approach with other types of graphics objects, such as surf
, but then you have to change the line that creates the object (first line in the code above). For example, with surf
it would be something like
Q = surf(NaN(2)); %// create object. surf needs matrix input
I have tested this in R2010b with plot
and with surf
.
copyobj
Use copyobj
to make a copy of the object in another (possibly invisible) figure, and then recover it from that. This automatically works for any object type.
%// Create the plot
P = plot(1:360, sind(1:360));
a = gca; %// get handle to axes
%// Make a copy in another figure
f_save = figure('visible','off');
a_save = gca;
P_saved = copyobj(P, a_save);
%// Delete the object
delete(P)
%// Recover it from the copy
P_recovered = copyobj(P_saved, a);
Upvotes: 5
Reputation: 13923
You can simply store the object as a struct PG
with the get
-command (as you already did) and then set all the parameters at once with the set
-command. There are some read-only fields, that need to be removed before setting them and the objects must be of the same type. In the following example, we create a plot with plot(0)
that is being overwritten with the data from the previous plot.
% Create the plot
figure
P = plot(1:360, sind(1:360));
% Store plot object
PG = get(P);
% Delete the plot
delete(P);
% Remove read-only fields of plot object
PG = rmfield(PG,{'Annotation','BeingDeleted','Parent','Type'});
% Create a new plot
figure
P = plot(0);
% Set the parameters
set(P,PG);
If you don't want to manually remove the fields, use a try-catch
-block and iterate over all the fields as described in Luis Mendo's answer.
Upvotes: 1