从 MATLAB GUI 保存绘图时包括轴标签

Include axes labels when saving plot from MATLAB GUI

我已经编写了以下代码来尝试从我的 MATLAB GUI 中仅检索轴及其绘图。

F = getframe(gca);
figure();
image(F.cdata);
saveas(gcf,'PlotPic','png');
close(gcf);

但是,我注意到此方法不包括我的任何轴标签或标题。有什么方法可以让 getframe 函数包含轴标签和标题?

我尝试了以下代码,但效果完全一样

pl = plot(x,y);
xlabel('x')
ylabel('y')

ftmp = figure;
atmp = axes;
copyobj(pl,atmp);
saveas(ftmp,'PlotPic.png');
delete(ftmp);

我会使用 getframe 函数的 rect 选项。

基本上,您可以向 getframe 提供第二个输入参数,然后捕获指定为参数的矩形的内容。好处是您可以使用轴的句柄,因此它不会捕获整个 GUI 图,而是捕获特定的轴。

例如,使用这一行:

F = getframe(gca,RectanglePosition);

具体来说,您可以设置矩形的坐标,使其跨越轴标签和标题。这是一个示例代码。按钮回调执行 getframe 并打开一个内容为 F.cdata:

的新图形
function GUI_GetFrame
clc
clear
close all

%// Create GUI components
hFigure = figure('Position',[100 100 500 500],'Units','Pixels');

handles.axes1 = axes('Units','Pixels','Position',[60,90,400,300]);
handles.Button = uicontrol('Style','Push','Position',[200 470 60 20],'String','Get frame','Callback',@(s,e) GetFrameCallback);

%// Just create a dummy plot to illustrate
handles.Period = 2*pi;
handles.Frequency = 1/handles.Period;

handles.x = 0:pi/10:2*pi;
handles.y = rand(1)*sin(handles.Period.*handles.x);

plot(handles.x,handles.y,'Parent',handles.axes1)
title('This is a nice title','FontSize',18);
guidata(hFigure,handles); %// Save handles structure of GUI.

    function GetFrameCallback(~,~)

        handles = guidata(hFigure);
        %// Get the position of the axes you are interested in. The 3rd and
        %// 4th coordinates are useful (width and height).

        AxesPos = get(handles.axes1,'Position');    

        %// Call getframe with a custom rectangle size.You might need to change this.
        F = getframe(gca,[-30 -30 AxesPos(3)+50 AxesPos(4)+80]);

        %// Just to display the result
        figure()
        imshow(F.cdata)        
    end
end

GUI 如下所示:

按下按钮后,弹出的图形如下:

因此,您唯一的麻烦就是计算出您需要 select 捕获轴标签和标题的矩形的尺寸。

希望能解决您的问题!