有没有办法将子图保存到 MATLAB 中的变量?

Is there any way to save a subplot to a variable in MATLAB?

在 matlab 的一段代码中,我生成了一个图形,其中出现了 5 个不同的子图。我希望可以将这些子图保存到变量中,这样我以后就可以调用其中一个子图,并在其自己的图中打开相同的子图(因此如果需要,可以更准确地查看它们)。不幸的是,我自己无法弄清楚如何做到这一点。

我知道可以按照此处描述的方式将整个图形保存到变量中:https://nl.mathworks.com/matlabcentral/answers/160049-how-to-assign-a-plot-to-a-variable

但这只会保存图形,只要它在您首次创建后保持打开状态。最重要的是,它没有说明如何对子图执行相同的操作。

我通过以下方式生成子图:


for i = 1:length(figuredata)
        subplot(2,3,i);                                           % select subplot
        plot(figuredata{1,i},figuredata{2,i},'r.') , grid on;     % plot the figure
        title(figuretitles{i});                                   % set title
        ylabel('SIN'), xlabel('COS'),grid on;                     % label the axes
        axis([0 16384 0 16384]);    axis('square');               % set axis range for x and y
end

其中 figuredata 是一个 2 x 5 元胞数组,包含 5 个绘图中每个绘图的数据,figurtitles 包含子绘图的标题

有没有人碰巧知道我怎样才能实现我想要的?

你首先需要了解的是graphics object handles的概念。在 MATLAB 中,handle 是对特定图形对象的引用。您使用句柄访问和更改对象的属性。句柄和实际对象本身应被视为独立(但相关)的实体。例如:

hFigure = figure();  % Create figure window and return handle
clear hFigure        % Clear variable containing handle

这将创建一个图窗 window 并将 window 的句柄存储在变量 hFigure 中,然后清除该变量。但是,图形仍然存在,因为我们只丢弃了引用该对象的句柄。或者:

hFigure = figure();  % Create figure window and return handle
delete(hFigure);     % Delete the graphics object
get(hFigure)         % Use handle to try and access the object properties
Error using matlab.ui.Figure/get
Invalid or deleted object.

这将创建一个图形 window,将 window 的句柄存储在一个变量中,然后删除该图形。删除对象后,句柄不再有效,如果尝试使用它会出错。

考虑到这一点,您可以使用几个选项来移动、保存和重新显示图形对象。假设您有一个现有的子图(即 axes object) that hasn't been closed or deleted, you can reparent the object to a new window by modifying the Parent property。例如:

hAxes = subplot(2, 2, 1);
plot(hAxes, [1 2], [1 2], 'r');
hFigure = figure();
set(hAxes, 'Parent', hFigure);

这将创建一个子图,然后将其移至新的 window。请注意,轴不再存在于原始 window 中,但它仍然具有与原来相同的位置、大小等。如果您希望它以不同的方式显示(即更大的图来填充新的window),您必须在移动它之后修改它的属性。

另一种方法是使用 copyobj 函数:

hAxes = subplot(2, 2, 1);
plot(hAxes, [1 2], [1 2], 'r');
hFigure = figure();
copyobj(hAxes, hFigure);

这将复制轴对象,因此现在有两个独立的图形对象,每个对象一个 window。

如果您正在处理原始图形将被关闭的情况,并且您想要保存坐标区对象的副本以便稍后重新显示它们,您可以使用 undocumented (or semi-documented) functions handles2struct and struct2handle. Here's an example that creates an axes with a line plotted in it, stores the axes object structure in a .mat file (using save), 然后加载结构并将其添加到新图形中:

hAxes = subplot(2, 2, 1);
plot(hAxes, [1 2], [1 2], 'r');
axesStruct = handle2struct(hAxes);
save('Axes_data.mat', 'axesStruct');

clear all;
close all;

load('Axes_data.mat');
hFigure = figure();
hAxes = struct2handle(axesStruct, hFigure);