Fred
Fred

Reputation: 60

Matlab GUI: How can I print out a plot in the user interface?

I have a interface in MATLAB which plots a curve by pressing button2. Now I can not print out the figure. More precisely, I want to add another button to print out the plot. Here is a piece of my code:

% --- Executes on button press in pushbutton2.
function pushbutton2_Callback(hObject, eventdata, handles)
% hObject    handle to pushbutton2 (see GCBO)
% eventdata  reserved - to be defined in a future version of MATLAB
% handles    structure with handles and user data (see GUIDATA)
%clear
%linkdata on
fileName = handles.fileName;

n_var=str2num(get(handles.n_var,'string'));

[x] = readColumns(fileName, n_var);

axes(handles.axes1);
hold on
plot(handles.axes1,x(1:n),'b','LineWidth',2)
hold off

Thanks.

Upvotes: 1

Views: 4009

Answers (1)

alrikai
alrikai

Reputation: 4194

It looks like you used GUIDE to make your GUI, so you should add your new button in the same manner (via GUIDE). Assuming that you have done so, in its callback function you'll want to have something like:

function printButton_Callback(hObject, eventdata, handles)
    fileName = handles.fileName;
    im = getframe(handles.axes1);
    %saves the image in variable "im" to a PNG file 
    imwrite(im.cdata, fileName, 'PNG')
end

the function getframe grabs a snapshot of the input handle parameter (in this case, your axes handle) and returns a structure with the image data ("cdata") and the colormap used for the frame. Then you write the image data to disk with imwrite, where fileName presumably is a string that has the filename you want, and 'PNG' tells imwrite the extension you want (you can also use BMP/GIF/JPEG or others)

Also as a slight nitpick, in your question you use figure and plot interchangably, but the figure will likely be differnt from the plot; namely, your figure will be your entire GUI, while the plot will be on your axes, which will be a child of your GUI.

EDIT: To preserve your axis labels, you might have to use a different method. Instead, what you could do is:

function printButton_Callback(hObject, eventdata, handles)
    fileName = handles.fileName;
    f_tmp = figure('visible', 'off');
    copyobj(handles.axes1,f_tmp);
    print(f_tmp, '-dpng', fileName);
    close(f_tmp);
end

This will create a hidden figure f_tmp, copy your plot on handles.axes1 to the hidden figure, then print it to a PNG file (specified by the flag '-dpng', you can use other extensions) named by the string fileName. At the end it closes the hidden figure. I think this would work, let me know if it doesn't

Upvotes: 1

Related Questions