Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Export Matlab figure as PNG?

I need to automatically export figures from Matlab to PNG. My figure has a size of 600x200 px:

hFig = figure(1); 
set(hFig, 'Color', [1 1 1]); % backgroundcolor white
set(hFig, 'Position', [500 500 600 200]) % size 600x200

I tried e.g.

print -dpng image.png

but the image.png is larger than 600x200 px. Exporting the figure manually from the Figure Window GUI using the "save" button works great, I want to do exactly this automatically / from a script. Thanks for any hint!

like image 474
stefan.at.wpf Avatar asked Jun 29 '12 12:06

stefan.at.wpf


1 Answers

My preferred approach for generating png plots from MATLAB is the export_fig utility available at the MATLAB file exchange.

Here's an example:

set(gcf, 'Position', [100 100 500 500], 'Color', 'w')

x=0:0.01:10;
plot(x, sin(x))
set(gca, 'FontSize', 20, 'FontName', 'Arial')

export_fig 'strip-diff-far-forward.png' -painters -nocrop

This will create a png that is 500 x 500 pixels, with 20 pixel fonts. I'm sure that internally it does the same kinds of things as in bdecaf's answer, but it is all ecapsulated in a function for you already, and has a bunch of other features too.

The drawback is that if you use the -painters renderer (which I think looks the best) you will need to have ghostscript installed. If you don't want to mess with that, you can change -painters to -opengl

Edit Now setting figure size correctly!

like image 137
Dan Becker Avatar answered Sep 21 '22 23:09

Dan Becker