重新绘制已删除对象的MATLAB



是否可以在删除后使用先前通过'get()'检索的属性重新绘制行?

例如:

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

我希望它是可推广的,即解决方案将适用于表面绘图,线条绘图,文本注释等

方法一:不要删除它,让它不可见

您可以使对象不可见,而不是删除和重新创建对象:

set(P, 'visible', 'off')

然后再次可见

set(P, 'visible', 'on')
方法2:使用loop创建对象并设置属性值

如果你真的想重新创建一个被删除的对象,你可以这样做:创建一个相同类型的对象,并使用for循环将其属性设置为存储的值。try - catch块是必需的,因为有些属性是只读的,会产生错误。

%// 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 

您可以对其他类型的图形对象(例如surf)使用此方法,但是随后您必须更改创建对象的行(上面代码中的第一行)。例如,对于surf,它应该是

Q = surf(NaN(2)); %// create object. surf needs matrix input

我已经在R2010b中使用plotsurf进行了测试。

方法3:复制对象并使用copyobj 进行恢复

使用copyobj在另一个(可能是不可见的)图形中复制对象,然后从中恢复它。这自动适用于任何对象类型。

%// 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);

您可以简单地使用get -命令将对象存储为结构体PG(就像您已经做的那样),然后使用set -命令一次性设置所有参数。有一些只读字段,在设置它们之前需要删除,并且对象必须具有相同的类型。在下面的示例中,我们使用plot(0)创建了一个图,该图被前一个图中的数据覆盖。

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

如果您不想手动删除字段,请使用try-catch块并遍历Luis Mendo的回答中描述的所有字段

最新更新