File Exchange

image thumbnail


version 1.1 (5.88 KB) by

Save *cropped* figures to pdf, eps, png, jpeg, and tiff through Ghostscript.

39 Ratings



View License

Usage: savefig(filename, fighdl, options)

Saves a pdf, eps, png, jpeg, and/or tiff of the contents of the fighandle's (or current) figure.
It saves an eps of the figure and the uses Ghostscript to convert to the other formats.
The result is a cropped, clean picture. There are options for using rgb or cmyk colours,
or grayscale. You can also choose the resolution.

The advantage of savefig is that there is very little empty space around the figure in the
resulting files, you can export to more than one format at once, and Ghostscript generates
trouble-free files.

If you find any errors, please let me know! (peder at axensten dot se)

filename: File name without suffix.

fighdl: (default: gcf) Integer handle to figure.

options: (default: '-r300', '-lossless', '-rgb') You can define your own
         defaults in a global variable savefig_defaults, if you want to, i.e.
         savefig_defaults= {'-r200','-gray'};.
'eps': Output in Encapsulated Post Script (no preview yet).
'pdf': Output in (Adobe) Portable Document Format.
'png': Output in Portable Network Graphics.
'jpeg': Output in Joint Photographic Experts Group format.
'tiff': Output in Tagged Image File Format (no compression: huge files!).
'-rgb': Output in rgb colours.
'-cmyk': Output in cmyk colours (not yet 'png' or 'jpeg' -- '-rgb' is used).
'-gray': Output in grayscale (not yet 'eps' -- '-rgb' is used).
'-fonts': Include fonts in eps or pdf. Includes only the subset needed.
'-lossless': Use lossless compression, works on most formats. same as '-c0', below.
'-c<float>': Set compression for non-indexed bitmaps in PDFs -
              0: lossless; 0.1: high quality; 0.5: medium; 1: high compression.
'-r<integer>': Set resolution.
'-crop': Removes points and line segments outside the viewing area -- permanently.
         Only use this on figures where many points and/or line segments are outside
         the area zoomed in to. This option will result in smaller vector files (has no
         effect on pixel files).
'-dbg': Displays gs command line(s).

savefig('nicefig', 'pdf', 'jpeg', '-cmyk', '-c0.1', '-r250');
Saves the current figure to nicefig.pdf and nicefig.png, both in cmyk and at 250 dpi,
         with high quality lossy compression.

REQUIREMENT: Ghostscript. Version 8.57 works, probably older versions too, but '-dEPSCrop'
         must be supported. I think version 7.32 or newer is ok.

Version 1.0, 2006-04-20.
Version 1.1, 2006-04-27:
- No 'epstopdf' stuff anymore! Using '-dEPSCrop' option in gs instead!
Version 1.2, 2006-05-02:
- Added a '-dbg' option (see options, above).
- Now looks for a global variable 'savefig_defaults' (see options, above).
- More detailed Ghostscript options (user will not really notice).
- Warns when there is no device for a file-type/color-model combination.
Version 1.3, 2006-06-06:
- Added a check to see if there actually is a figure handle.
- Now works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).
- Now compatible with Ghostscript 8.54, released 2006-06-01.
Version 1.4, 2006-07-20:
- Added an option '-soft' that enables anti-aliasing on pixel graphics (on by default).
- Added an option '-hard' that don't do anti-aliasing on pixel graphics.
Version 1.5, 2006-07-27:
- Fixed a bug when calling with a figure handle argument.
Version 1.6, 2006-07-28:
- Added a crop option, see above.
Version 1.7, 2007-03-31:
- Fixed bug: calling print with invalid renderer value '-none'.
- Removed GhostScript argument '-dUseCIEColor' as it sometimes discoloured things.
Version 1.8, 2008-01-03:
- Added MacIntel: 'MACI'.
- Added 64bit PC (I think, can't test it myself).
- Added option '-nointerpolate' (use it to prevent blurring of pixelated).
- Removed '-hard' and '-soft'. Use '-nointerpolate' for '-hard', default for '-soft'.
- Fixed the gs 8.57 warning on UseCIEColor (it's now set).
- Added '-gray' for pdf, but gs 8.56 or newer is needed.
- Added '-gray' and '-cmyk' for eps, but you a fairly recent gs might be needed.
Version 1.9, 2008-07-27:
- Added lossless compression, see option '-lossless', above. Works on most formats.
- Added lossy compression, see options '-c<float>...', above. Works on 'pdf'.
  Thanks to Olly Woodford for idea and implementation!
- Removed option '-nointerpolate' -- now savefig never interpolates.
- Fixed a few small bugs and removed some mlint comments.
Version 2.0, 2008-11-07:
- Added the possibility to include fonts into eps or pdf.

TO DO: (Need Ghostscript support for these, so don't expect anything soon...)
- svg output.
- '-cmyk' for 'jpeg' and 'png'.
- Preview in 'eps'.
- Embedded vector fonts, not bitmap, in 'eps'.

Copyright (C) Peder Axensten (peder at axensten dot se), 2006.

Comments and Ratings (51)

I had to change the value of `DeviceRGB' to `eps2write' in order to get .eps output.

The .eps output does not appear to be cropped despite using the `-crop' option.

My system is: W7 64-bit, Matlab R2013b, gs 9.18

A typical call is: savefig(ffn, gcf, fmt, '-rgb', '-r350', '-crop') where fmt is 'eps'.

Your submission is well used and appreciated.



Diane (view profile)

Get this warning:
"Since the release of version 9.11 of Ghostscript we recommend you do not set
-dUseCIEColor with the pdfwrite/ps2write device family."

I removed this flag from line 121 to make the warning go away. The output appears to be unchanged.


Gar (view profile)


Andrea (view profile)

Auto-crop doesn't work as well with Yosemite and Matlab R2014b.


Thomas (view profile)

Byron. To incorporate this feature enter the following on line 225:

"fix_lines([fname '-temp.eps']);"

The program will run fix_lines before converting to other formats.


Thomas (view profile)

Alex. R. This can be easily fixed by renaming the version of this file as something like "savefig_exchange.m"

Alex R.

Alex R. (view profile)

This now conflicts with 'savefig' which is included in Matlab R2013b


Helge (view profile)


Byron (view profile)

The auto-crop is a great utility! I highly suggest incorporating a call to something like fix_lines.m inside this function to improve the dotted/dashed lines in the temporary eps file! I wish that the size of exported dotted/dashes in lines was affected by resolution the way it is with the print.m function, but at least fix_lines.m helps improve the dotted/dashed lines some.


Amir (view profile)


Oscar (view profile)


Excellent job! This file saves me plenty of time. Thank you.


Thanks for this nice routine.
In order to make it work under Windows7-64 bits, I had to change line 207 to;

case {'PCWIN','PCWIN64'},gs= '"C:\Program Files\gs\gs9.02\bin\gswin64.exe"';

and than add this ghostscript64 folder to my Matlab path


Marco (view profile)

Great, very useful since latex doesn't like command produced pdf and png documents!


Joakim (view profile)

Great, this is what I've been looking for!

Any idea how to make the labels and "ticklabels" less clumsy? They are pretty large and bold looking.



David (view profile)

If your system can't access gs then put the directory (in which gs is) to the PATH environment variable.


Thomas (view profile)

Phenomenal effort here!! I had been trying to figure out how to do this for months.

One bug that I had to fix:
I am running Mac OS X V10.6.8. In the code, the "Switch computer" (Line 205) was reading MACI64. I had to change the the resulting case to include this option. Specifically, I appended Line 206 to read: "case {'MAC','MACI64'}, gs= '/usr/local/bin/gs';".

Otherwise, things work like a charm.

Possible improvements: figure size control.


Perfect, many thanks


Theo (view profile)

Thank you to Emily for providing the fix for 64-bit Matlab for Mac. (21 Jun 2011)


Georg (view profile)


Emily (view profile)

Great program. It works for 64-bit Matlab for Mac if you add 'MACI64' to line 206. Before I did that I was getting 'gs: command not found' errors.

Pretty cool, but isn't setup to work with 64-bit it seems.


Johan (view profile)

how do you import the file into Matlab?


jiddu (view profile)

Thanks for posting this program.
Is there a way to add Labels and a Title to the figure, prior to saving it?


This is a great program. I use it almost every day. It works well 99% of the time. Sometimes, if there is a really complicated plot, it does not export PDF as a vector file. In those cases, I use Matlab's print command to eps and then let Mac OS X convert the eps to pdf. Even eps2pdf command line doesn't do it.

Do you know what makes it fail to export vector images sometimes?

Either way, great program.

John Deas

Is it possible to change the lines thickness ? They seem a little bit more thick than what I have on screen, and when there are a lot of them as with the contour function, it doesn't look as clear.

Aaron Swan

Just in case someone runs into this, MATLAB crashes when I try to use savefig to save a figure with transparent patch graphics.

Aaron Swan


Dylan (view profile)

I'm using this script to export figures to pdf. The figures have an image background, with vector elements (dots) overlaid. Sometimes the vector elements are kept as vectors, sometimes they are merged with the image... and I can't work out why, or how to force vector elements to be retained. It may have to do with the complexity of the figure. Any suggestions would be appreciated. Otherwise, great script!


Salman (view profile)

just great

Oliver Woodford

With the ability to change compression quality for bitmaps in pdfs, this is now perfect. Highly recommended alternative to Matlab's PRINT.

A Muir

Great little script. The real question is why the built in Matlab graphic export is so incredibly bad in the first place. thankyou for correcting their mistakes

Michal Aftanas

Simply great, exactly what I was looking for a long time. Good job

Oliver Woodford

I should clarify that my previous comment was specific to saving images overlaid with vector graphics to pdf, which is probably quite a niche requirement.

DS .

Functional and very handy code. There appear to be some issues with regard to proper cropping of figures, however. Possibly a ghostscript issue, but when saving as a .tif image the procedure produces uneven padded borders. Saving and 1024x512 pixel .tif at 150dpi gives me border padding of 1,7,7, and 2 pixels, respectively (using GPL Ghostscript 8.62).

Claudio Piciarelli

simply great, it's exactly what I was searching for and it works fine :)

Oliver Woodford

Very nice, but could do with having more options for compression when converting to pdf (and also jpeg, I guess) - e.g. lossless, high, medium, low - as the default setting is pretty low quality/high compression. For my purposes I needed higher quality output though.

I figured out how to do this myself, so if you want the gs incantations for this I can send them to you.

Ben S

This program does exactly what Matlab should do with graphic exports.

Why does Matlab decide to completely chew up graphs when exported directly to .pdf? And if you export through .eps and use epstopdf you get an idiotic bounding box. Matlab has the ability to set up page size and attributes in the page setup menu, but not in the export setup menu. And they don't seem to be in any way related with regards to pdf's. Pretty poor.

Anyway, this program fixes all that. But, I had a problem whereby it didn't recognise my gs file location so I had to copy gswin32c.exe into my working Matlab folder. Fine now.

Derek O'Connor

I forgot to add this in my previous post.

For Windows Vista 64 : after line 93, add a copy of line 93 with 'PCWIN' changed to 'PCWIN64'

Derek O'Connor

This is top class. Tight bounding box and small file size (eps).

QUESTION : Why doesn't Matlab get it right?

Tom D

Great stuff! This functionality really ought to be included in MATLAB. By default, savefig interpolates images, which can be undesirable when plotting discrete data like 2-D histograms. A quick fix is to delete -dDOINTERPOLATE from line 98. I have sent Peter an email requesting him to make this behavior be controlled by a switch

Martin Hemberg

Great. Does what it says without any problems

Felix Hebeler

Forgot to rate last time. Nice script. Would be good if one could specify fontsize. I use a workaround atm, opening the export figure dialog and selecting (and applying) font size there, then use savefig

Dan Hemberger

This is a great file. It is exactly what I was looking for. I wanted to use PDF files from Matlab with pdflatex, but I was encountering bounding box issues.

A note, however: I had to include the path to Ghostscript .exe in the script.

Felix Hebeler

Great, I wish I had looked earlier... finally 4 figures do have the same extent, colorbarbwidth and readable font. If only grayscale would work for eps and pdfs...

Simone Hochgreb

Brilliant. I wish I hadn't spent so much time trying to fix matlab bugs. Thank you.

Raphael P

very easy to use. great interface, and great results.


Very easy to use - works well

Ted Rosenbaum

I second the previous comment, this produces very clean and properly trimmed eps files for inclusion in latex.

M. Tetouan

Excellent! The default cropping option is very useful for LaTeX and PowerPoint users.



- Added the possibility to include fonts into a pdf.

- Added MacIntel.
- Added 64bit PC.
- Added option '-nointerpolate'.
 - Removed '-hard' and '-soft'.
- Fixed the gs 8.57 warning on UseCIEColor.
- Added '-gray' for pdf.
- Added '-gray' and '-cmyk' for eps.

- Fixed bug: calling print with invalid renderer value '-none'.
- Removed GhostScript argument '-dUseCIEColor' as it sometimes discoloured things.

Added a crop option.

Fixed a bug when calling with a figure handle argument.

- Added an option '-soft' that enables anti-aliasing on pixel graphics (on by default).
- Added an option '-hard' that don't do anti-aliasing on pixel graphics.

- Added a check to see if there actually is a figure handle.
- Now works in Matlab 6.5.1 (R13SP1) (maybe in 6.5 too).
- Now compatible with Ghostscript 8.54, released 2006-06-01.


- Added a '-dbg' option.
- Now looks for a global variable 'savefig_defaults'.
- More detailed Ghostscript options.
- Warns when there is no device for a file-type/color-model combination.

MATLAB Release
MATLAB 7.4 (R2007a)

Download apps, toolboxes, and other File Exchange content using Add-On Explorer in MATLAB.

» Watch video