Save a plot to a JPEG file in Matlab

13,297

Solution 1

saveas only saves figures, not individual plots.

If you have a subplot, or a plot within a uicontrol like you have, you can make a temporary copy of the plot, save it, then delete the temporary copy:

ftmp = figure; atmp = axes;
copyobj(hplot, atmp);
saveas(ftmp, FileName);
delete(ftmp);

If you don't want the temporary copy to flash up on the screen during the copying step, you can use the 'Position' property of the figure to create it off-screen.

Hope that helps!

Solution 2

@Sam's answer is spot on, I just want to add that Matlab is smart enough to know what kind of file you want to save by inspecting the FileName string variable. If you set FileName to something that ends in .jpg, you can save a jpeg. Check out the saves docs to see all the other possible filetypes.

Solution 3

When using the saveas function to create jpeg the resolution is different as when manually saving the figure with File-->Save As..., It's more recommended to use hgexport instead, as follows:

hgexport(gcf, 'figure1.jpg', hgexport('factorystyle'), 'Format', 'jpeg');

This will do exactly as manually saving the figure.

source: http://www.mathworks.com/support/solutions/en/data/1-1PT49C/index.html?product=SL&solution=1-1PT49C

Share:
13,297
julianfperez
Author by

julianfperez

BY DAY: Full Stack Java Developer and MEng Aerospace Engineer. BY NIGHT: Superhero, DJ. FOR FUN: Blogger, Writer, Poet, Actor. “I am not a product of my circumstances. I am a product of my decisions.” - Stephen R. Covey

Updated on June 04, 2022

Comments

  • julianfperez
    julianfperez almost 2 years

    I have designed the following GUI in which there are an axes. I want to save the plot drawn inside them to a jpeg file. However, the file obtained is an image of the overall figure window. This is my code:

        X = 0:pi/100:2*pi;
        Y = sin(X);
        fh = figure;
        Pan1 = uipanel(fh,'Units','normalized','Position',[0 0 0.5 1],'title',...
            'Panel1');
        Pan2 = uipanel(fh,'Units','normalized','Position',[0.5 0 0.5 1],'title',...
            'Panel2');
        haxes = axes('Parent',Pan2,'Units', 'normalized','Position',...
            [0.25 0.25 0.5 0.5]);
        hplot = plot(haxes,X,Y);
        xlabel(haxes,'Time (second)');
        ylabel(haxes,'Amplitude (meter)');
        title(haxes,'Sine function');
        FileName = uiputfile('*.jpg','Save as');
        saveas(hplot,FileName);