Code covered by the BSD License  

Highlights from
export_fig

4.95531

5.0 | 199 ratings Rate this file 2563 Downloads (last 30 days) File Size: 26.4 KB File ID: #23629
image thumbnail

export_fig

by Oliver Woodford

 

11 Apr 2009 (Updated 22 Mar 2013)

Exports figures nicely to a number of vector & bitmap formats.

Editor's Notes:

This file was selected as MATLAB Central Pick of the Week

| Watch this File

File Information
Description

This function saves a figure or single axes to one or more vector and/or bitmap file formats, and/or outputs a rasterized version to the workspace, with the following properties:
   - Figure/axes reproduced as it appears on screen
   - Cropped borders (optional)
   - Embedded fonts (pdf only)
   - Improved line and grid line styles
   - Anti-aliased graphics (bitmap formats)
   - Render images at native resolution (optional for bitmap formats)
   - Transparent background supported (pdf, eps, png)
   - Semi-transparent patch objects supported (png only)
   - RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff)
   - Variable image compression, including lossless (pdf, eps, jpg)
   - Optionally append to file (pdf, tiff)
   - Vector formats: pdf, eps
   - Bitmap formats: png, tiff, jpg, bmp, export to workspace

This function is especially suited to exporting figures for use in publications and presentations, because of the high quality and portability of media produced.

Note that the background color and figure dimensions are reproduced (the latter approximately, and ignoring cropping & magnification) in the output file. For transparent background (and semi-transparent patch objects), use the -transparent option, and set the axes 'Color' property to 'none' where desired. Pdf, eps and png are the only file formats to support a transparent background, whilst the png format alone supports transparency of patch objects.

When exporting to vector format (pdf & eps), and to bitmap using the painters renderer, this function requires that ghostscript is installed on your system. You can download this from:
   http://www.ghostscript.com
When exporting to eps it additionally requires pdftops, from the Xpdf suite of functions. You can download this from:
   http://www.foolabs.com/xpdf

Usage examples can be found at:
http://sites.google.com/site/oliverwoodford/software/export_fig

When reporting bugs, please use the 'Contact Author' link on my Author page, rather than pasting the error into the comments - I will respond more quickly, especially if I can email you back.

Acknowledgements

Savefig, Fix Dashed And Dotted Lines In Eps Export, Fixpslinestyle, Myaa My Anti Alias For Matlab, and Fix Lines inspired this file.

This file inspired Google Earth Overlay, Convert Plot4 Publication, Append Pdfs, Causal State Modeller Toolbox, Machine Learning Balancing A Stack Of Balls, Fast And Efficient Spectral Clustering, Co Blade: Software For Analysis And Design Of Composite Blades, Matlab Icon For Linux (With Transparency), Multiple Colormaps, Export Figure To 3 D Interactive Pdf, Color Checker Chart, and Eps Utility Toolbox.

MATLAB release MATLAB 7.13 (R2011b)
Other requirements Ghostscript, Xpdf
Tags for This File  
Everyone's Tags
Tags I've Applied
Add New Tags Please login to tag files.
Please login to add a comment or rating.
Comments and Ratings (319)
19 Apr 2013 Greg

Great set of functions! May I propose an improvement of "eps2pdf" ?
I had to add this at line 54 (after crop cmd) in order to modify the final pdf orientation:

options = [options ' -dEPSCrop -c "<</Orientation 3>> setpagedevice"'];

Maybe the orientation could be given as an input argument?

For information:
* -c "<</Orientation 3>> setpagedevice" -- sets landscape orientation;
* -c "<</Orientation 0>> setpagedevice" -- sets portrait orientation;
* -c "<</Orientation 2>> setpagedevice" -- sets upside down orientation;
* -c "<</Orientation 1>> setpagedevice" -- sets seascape orientation.

19 Apr 2013 Greg  
19 Apr 2013 Greg  
12 Apr 2013 arnold

latex formulas are distorted/upscaled and displayed incorrectly, but they appear right in the actual figure.

example:
======================
text(xpos,ypos,'$$\frac{\alpha}{\sqrt{2}}\cdot', num2str(1e5),'s$$','HorizontalAlignment', 'left', 'BackgroundColor', [.7 .9 .7], 'interpreter','latex');
======================
it looks right in the figure yet, when export_fig is used, the output image (of whatever kind) shows:

- latex formula is scaled up = bigger
- background of formula doesn't fir anymore (because it's not scaled)
- latex formula is buggy, the '2' is upscaled, yet the square root is not

Maybe you can get around to implementing this as well. Makes it a bit useless for me since I usually have to have formulas in my legends or annotations.

10 Apr 2013 Oliver Woodford

Michael: Note that export_fig does not transparency in patch objects in vector formats. Only a transparent background is supported.

10 Apr 2013 Michael

I would love to use this tool to export vectorized eps with transparency, unfortunately I am running a Mac and I seem to require pdftops. I get this error message: "Pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/"

The link suggested is dead unfortunately, and after long google searches I found no alternative. Does somebody know a link that works?

10 Apr 2013 Wouter

Use this submission daily. Should be incorporated in Matlab!

28 Mar 2013 yuhua zou

Great! It provides what I need!

15 Mar 2013 Viktar Tatsiankou  
14 Mar 2013 arnold

nice job!

Do you think you could add the ability to change all fonts in the figure to a certain one? Would be really useful when exporting figures for publications that use a certain font, to keep a consistent look.

13 Mar 2013 arnold  
09 Mar 2013 Laura

Sorry. my fault. problem solver. Export_fig working perfectly:)

08 Mar 2013 Laura

Hi!!
Very nice tool! However I am having a problem that couldn't solve so far...and it is driving me a bit crazy. Export_fig is changing the sizing of my figures so that the aspect ratio is altered! Could someone tell me why or how to avoid it? I need to print it exactly with the size it is defined,

Thanks

02 Mar 2013 Wouter  
25 Feb 2013 LY Cao

great work!
but I found something wrong:
scatter(rand(10,1),rand(10,1),50);
export_fig('1.png',gca)
and the axes in 1.png is empty.
the matlab function allchild can't find the children of a handle whose type is 'hggroup'(e.g. scatter hggroup).
I modified the allchildren function in isolate_axes.m:
function ah = allchildren(ah)
ah = allchild(ah);
if iscell(ah)
ah = cell2mat(ah);
end
ah = ah(:);
for i = 1:numel(ah)
if strcmp(get(ah(i),'type'),'hggroup')
t =allchildren(ah(i));
ah(end+1:end+numel(t)) = t;
end
end
return
and it worked.

25 Feb 2013 Sauro Salomoni  
23 Feb 2013 David Verrelli

Hi, Oliver,
I had played around with the relevant commands to copy figures as high-resolution bitmaps, using the undocumented "hardcopy" function suggested by TMW staff
e.g. hardcopy(hF_StatsAVI, '-Dopengl', '-r100')
In comparison, your function is more convenient to use, and much better documented.

I am using it to save out PNG files with either whigte or transparent figure background. However, I was baffled when running the same commands which had been succesful previously began outputting images with black backgrounds, despite my setting
set(gcf, 'color','white');
The problem seems to be that it is necessary to _manually_ select "Use figure color" in the "Copy Options" dialogue box, under "Edit" from the figure's menu bar.
I would normally want to produce a metafile with "Transparent background" when _copying_ the figure, except for some recalcitrant plots; hence, I don't usually have "Use figure color" selected.
I thought it might be possible to toggle this programatically, but the command
set(gcf, 'InvertHardCopy', 'off');
was not effective.

Anyway, these issues seem to point to flaws in MATLAB, rather than in your code.

~~~~~

By the way
set(gcf, 'color','none');
is generates this message:
"Warning: Setting the ColorSpec to 'none' for a figure will not be allowed in a future release."
It still works at the moment, and personally I would rather it continued to work. I hope it is replaced by an alternative, and not just removed.

—DIV

18 Feb 2013 Max

In case anyone cares: solved my problem by writing '\circ' instead of '°'. Exports fine now :)

14 Feb 2013 Max

I like and use this a lot, thanks for the submission!
However, the degree symbol (°), which is part of the axis label on one of my plots, does not appear in the vectorized PDF. Is this a known issue? Are there any suggestions on how to deal with it?
Found a similar issue here: http://modb.oce.ulg.ac.be/mediawiki/index.php/Matlab/Octave_scripts#Incomplete_satellite_images
Maybe they are related...

11 Feb 2013 Ali Hummos

Outstanding!

10 Feb 2013 Arindam Bose  
08 Feb 2013 Max  
04 Feb 2013 Dmytro

Great thing, absolutely musthave! Use it a lot.

I would also like to report a minor, although sometimes very annoying, bag:
when used with zbuffer, anti-aliasing does not work well with LaTeX text, corrupting it and changing its size and shape. To see this, try to export some figure with both 3D-surfaces and some LaTeX-rendered labels ("export test.tiff -a2 -zbuffer;"). It would be great if this can be fixed!

28 Jan 2013 Damjan Miklic

Great piece of software. A must-have for scientific publishing!

28 Jan 2013 guo

thx very much. very useful and enlightening!

18 Jan 2013 Yan Jiang

A must have for scientific researchers!

09 Jan 2013 Salman Mashayekh  
05 Jan 2013 Christian

export_fig did exactly what I needed.

I had to change the file user_string.m though, because it failed to write the settings. MATLAB said "error: Error using ==> fwrite: Invalid precision.", so I replaced fwrite with fprintf.

The correction can be found here.
https://www.dropbox.com/s/g139kxk08845qxa/user_string.m

20 Dec 2012 Tobias Lamour

Oubeid,

if you read all the description above you will discover the following lines towards the end:
"Usage examples can be found at:
http://sites.google.com/site/oliverwoodford/software/export_fig”

If you follow Oliver’s link with the examples you will find towards the end of the page the example below, which exactly provides what you would like to do:

Variable file names:

for a = 1:5
plot(rand(5, 2));
export_fig(sprintf('plot%d.png', a));
end

Good luck!

19 Dec 2012 Oubeidillah

Thanks for sharing this useful program.
A quick question:
I am saving multiple figures with different name in for loop. Is it possible to use a name that is dynamically created depending on the value of the loop iteration like ['name' int2str(i)] -jpg ?

Thanks

Oubeid

12 Dec 2012 Ratish Punnoose

Oliver, you are possibly correct. I may have made the change in an earlier version to let my cygwin install work with it (and then forgotten about it). Thanks for incorporating the change. That will make it work well with cygwin.

12 Dec 2012 Oliver Woodford

Ratish: The code was never previously as you say it was. However, I will implement the change you suggest.

michael: It's currently unsupported. I'll look into implementing it.

08 Dec 2012 michael

Sir,
Really nice function, nice job !!

I'm trying to export an uipanel which contains multiples plots/ axes. Your function can only pass handle or axes. Is there any way to pass a uipanel ?

regards,

Michael

07 Dec 2012 Bahaa  
26 Nov 2012 Ratish Punnoose

Latest version (Nov 5 2012) breaks usage of ghostscript in cygwin.

In ghostscript.m, the following line
if ispc
bin = {'gswin32c.exe','gswin64c.exe', 'gs'};
else ...

got changed to
if ispc
bin = 'gswin32c.exe','gswin64c.exe'};
else ...

That stopped export_fig from being able to use the ghostscript packaged with cygwin on windows.
Restoring 'gs' to the array fixes this.

26 Nov 2012 University Dschang

Hi, i would like to read a grd file of gridgen software using matlab.Thanks!

21 Nov 2012 Jonathan  
20 Nov 2012 Anoosha papireddy  
13 Nov 2012 zhr

2Aleg: try to use
orient portrait
before export_fig. It helps for me but I can't test your code now.

13 Nov 2012 Oliver Woodford

Aleg: The second sentence of the file description reads "Figure/axes reproduced as it appears on screen". Also there is no mention of a 'PaperOrientation' option in the ample help text.

13 Nov 2012 Aleg

I try to create a pdf file with a figure and it always creates file landscape orientation. No matter what parameters I put in place. Code example:

figure('PaperSize',[20.98404194812 29.67743169791]);
plot(AvgIndustryLP(1:end,1),'-g');
set(gcf, 'Color', 'w');
export_fig ('PaperOrientation','portrait','test.pdf')

Does any one know how to define paper orientation for pdfs in export_fig?

Thanks

09 Nov 2012 Cesar

For some reason, explicitly specifying the -r150 option fixed the issue. However since export_fig does not pass the -r argument when generating an eps file, I modified it by adding code around line 401 as follows:
p2eArgs = {renderer};
if options.magnify ~= 1
p2eArgs = [p2eArgs {['-r',num2str(options.magnify*get(0, 'ScreenPixelsPerInch'))]}];
end

Of course this fixed only my issue and probably needs to be verified.

This is strange since "print" uses -r150 by default according to the documentation.

Thanks for the great script!

08 Nov 2012 Cesar

Great work!!
Just one issue.
I am also using addTopXAxis.m (File ID: #9046) to add a second x axis with a label on top of the plot.
When I use your script to save to a PDF file, the second x label is not printed.
Any hints as to why this is happening and how to to correct it?

Thanks for your great script.

06 Nov 2012 Long Nguyen  
02 Nov 2012 Ashvin Kumar  
25 Oct 2012 Alan Chen  
25 Oct 2012 masiat

YEAH! Best submission ever on the fileexchange! It made my day and saved me from jumping off a bridge while trying to finish my phd thesis!
This seems to be the *only* way to export figures in a reasonable resolution without *very strange* gridlines. The author did an excellent work which the people on mathwork have somehow missed over many years!

22 Oct 2012 Cahaya  
17 Oct 2012 Michael Steinbock

Indispensible tool!! I do have one issue with saving vector figures that have overlaid lines. The white lines turn a dark blue when I save to pdf or eps (but not png). The code below demonstrates:

figure
imagesc(peaks(128))
hold on
plot(1:128, 1:128, '-w', 'linewidth', 2)
hold off
export_fig('-painters', '-r600', '-q101', 'test.pdf')

16 Oct 2012 Juan Cardelino  
16 Oct 2012 Malcolm Hudson  
13 Oct 2012 John

Great script, thanks for your work!

05 Oct 2012 Koen

A wonderful file. This is so much better than the native matlab functions! Now I can finally print figures for publications without a whole lot of re-editing and tweaking to make them look just right.

03 Oct 2012 Olivier  
29 Sep 2012 Karl  
26 Sep 2012 twimmeh  
24 Sep 2012 dbdq

Thanks to this utility, now I can export my images on background with native resolution! Thanks a lot!

24 Sep 2012 dbdq

Thanks to this utility, now I can export my images on background with native resolution! Thanks a lot!

18 Sep 2012 Kami  
18 Sep 2012 Kami  
16 Sep 2012 Laurent  
12 Sep 2012 Sam Johnson

This function is a life saver. I now use it for every publication ready figure as the output is exactly as I see it in MATLAB and sometimes even better!

Thank you.

10 Sep 2012 James Gwilliam

Is there a way to include a URL in a PDF file from export_fig that will work as an active hyperlink in the resulting PDF file?

07 Sep 2012 Rodolphe

Great Job and great function. !
Is there a way to export in pdf/eps with the -transparent option but without the painters renderer?

27 Aug 2012 Will Fonseca

Found the solution of my question ans extra help in:
https://sites.google.com/site/oliverwoodford/software/export_fig

27 Aug 2012 Michal Ficek

Good job! Something that finaly works as I expected. Thanks!

10 Aug 2012 Will Fonseca

This package is perfect for exporting figures.
However, I have one issue.
How can I export several pictures ?
Because whatever I put after "export_fig" will turn into a string, so I cannot include a name that increases with one variable.

Can anyone point me a solution ?

Thank you very much.

10 Aug 2012 Will Fonseca  
08 Aug 2012 David Wang

I found the pdf figures (4-panel pcolor plots) that export_fig creates on a linux box are rendered very slowly in Preview on my macbook pro (mac os x snow leopard). Does anyone encounter a similar issue? I wonder what's the cause of the problem. The pdf figures are not particularly large (about 5 MB each). Thanks.

08 Aug 2012 Sandrine  
01 Aug 2012 Ratan  
24 Jul 2012 Todd Karin

Hello Oliver,

I have an image that is 40 x 40 pixels. In the matlab figure window, the pixels are crisply separated from one another, but I can't get your code to export a pdf with the pixels cleanly separate. Do you have any suggestions for how to save the figure exactly as it is in the matlab figure window? To see what I mean, try:

figure
imagesc(peaks(40))
export_fig('test.pdf','-q1000')

23 Jul 2012 Jessica Lam  
22 Jul 2012 Ileana

Thanks! great work
http://www.mathworks.com/matlabcentral/fileexchange/feedbacks/new?id=23629&rating=5&stamp=1342975977work

18 Jul 2012 JR King

Impressively efficient.
However, it doesn't export changes of line width for transparent patches, even in png.

Thanks

18 Jul 2012 Ryan

Well done - robust, continually updated and works great!

16 Jul 2012 Oliver Woodford

Pavel: set the figure size to the size of output you want, e.g. 3x4 inches. Then specify the output resolution you want in the call to export_fig. Simple.

15 Jul 2012 Pavel

I see that the pixel size or size in inches of the produced question has been a subject of discussion. What's the status as of 7/2012? I find that no matter what I try, my PNG comes out the same size (in inches). Then, if I scale it down afterwards, line art and text get affected.

The desired behavior for me is as follows: I get to specify the size (e.g. 3"x4") and the resolution (e.g. 200 dpi). The text size is adjusted so that, proportionally, it looks the same as in the figure. Same for the thickness of line art. However, the higher the resolution, the higher the quality of lines (by affecting the aliasing, I suppose).

Is this achievable? I'm willing to go into the code and modify it.

Thank you for this great script.

15 Jul 2012 Pavel

I see that the pixel size or size in inches of the produced question has been a subject of discussion. What's the status as of 7/2012? I find that no matter what I try, my PNG comes out the same size (in inches). Then, if I scale it down afterwards, line art and text get affected.

The desired behavior for me is as follows: I get to specify the size (e.g. 3"x4") and the resolution (e.g. 200 dpi). The text size is adjusted so that, proportionally, it looks the same as in the figure. Same for the thickness of line art. However, the higher the resolution, the higher the quality of lines (by affecting the aliasing, I suppose).

Is this achievable? I'm willing to go into the code and modify it.

Thank you for this great script.

14 Jul 2012 Alexander Farley

Works as expected first try.

13 Jul 2012 Fabio Gori

Very helpful! But it didn't crop properly when my ylabel was longer than they y axis.

05 Jul 2012 Jeff Evans

Fantastic. I've been using this for several years, and it works perfectly. What you see on the screen is what you get in your exported figure.

Why Mathworks can't develop and implement something that works this well is a mystery to me. I guess as long as you'll do it for free, they don't have to...

Many Thanks

03 Jul 2012 rito

very helpful set of codes! Super well documentation and ease of use. Thanks.

21 Jun 2012 Kevin Moerman

I've a semi-transparent surface (triangulated patch data and the renderer is opengl) with curves on it (plot3 lines). When I use:
export_fig('temp.png','-r100');
to create the figure the lines get thinner with respect to the image content as a function of the resolution. Increasing line width does not seem to have an effect. Is there a way to fix/set line thickness?

Thanks

20 Jun 2012 Javier

Hi,

when I save a figure in png a gray border appears, how can I avoid this?

Thank you

15 Jun 2012 Mathieu

Best package out there to save vector graphics. Highly recommended!

31 May 2012 Hamidreza Nourzadeh  
24 May 2012 Zhiyong

Was having trouble saving figures in high resolution, since there seem to be no inbuilt functions that allow this. This user-created function was great. I have an enquiry on the '-native' option of export_fig. Seems like one must specify the desired high resolution himself.

22 May 2012 Haonan Chen

good job

08 May 2012 Hin Kwan Wong  
08 May 2012 Hin Kwan Wong

Thanks, works great. I've tried mat2pgf, mat2tikz, fig2texps, mlf2pdf, none worked with a complex figure I have. This works perfect.

07 May 2012 Antoine C

Thanks a lot for sharing that powerfull founction.

03 May 2012 b

Hi,

This is the first time off exchange I am trying to use.
I have copied the zip content into my current folder. It still prompts that it cannot find the functions. Even after again adding the path, it cannot find pdftops even though I see it in the directory.

As I need transparency, I cannot use painters or zbuffer. Should I expect quality improvement with this set of tools then?

In the meantime, how do I save a pdf of the figure only and not a page?

Cheers

25 Apr 2012 John

I am wondering if anyone has found a good technique for using export_fig to automatically paste figures into a word document. i use save2word often, but haven't figured out how to link the two up. Also, I must be doing something wrong with the resolution, so if anyone has a good example of how to get good resolution (for a .PNG maybe?) I would appreciate the advice.

22 Apr 2012 b

Hi,

This is the first time off exchange I am trying to use.
I have copied the zip content into my current folder. It still prompts that it cannot find the functions. Even after again adding the path, it cannot find pdftops even though I see it in the directory.

As I need transparency, I cannot use painters or zbuffer. Should I expect quality improvement with this set of tools then?

In the meantime, how do I save a pdf of the figure only and not a page?

Cheers

10 Apr 2012 Oliver Woodford

none: Currently fontnames are case sensitive. Use 'Symbol'.

09 Apr 2012 none

hi oliver.

great bit of code. I have been using it for years.

I think I may have just found a bug though:

I am running MATLAB 2010B on win7 (64bit).

if you run:

figure;
T = 2048;
x=randn(1,T);
plot(x)
set(gca, 'YTick', [-1 0 1])
str2={'-p' ' 0' '+p'};
set(gca,'YTickLabel',str2,'fontname','symbol');
export_fig('D:\test', '-PDF');

you see that export_fig "unconverts" the symbol back to plain text and exports it as plain text.

can you comment on this?

I have also posted on the matlab site so others can see too.

best wishes

08 Apr 2012 Scott

Handy! One suggestion: if the output directory doesn't exist, offer to make it. I expected this because it already makes directories for the different file types.

04 Apr 2012 sam p

Great job.!!

29 Mar 2012 John Reinert Nash  
28 Mar 2012 Estee  
28 Mar 2012 Estee

For a long time I've been frustrated that saving .fig's will result in (for some reason) 3D sized images that are not the same size as the original image! This function is awesome, thanks!

20 Mar 2012 Andrey  
18 Mar 2012 Bosheng

I like the transparency!!

09 Mar 2012 Yuri Kotliarov

Thanks, Oliver. I've solved the problem by using colors from colormap. Thanks for surely the best submission. (Just found that I haven't rate it yet.)

08 Mar 2012 Oliver Woodford

Yuri: Please, this is not the place for bug reports; see my comments on emailing me directly. I have added a note on this issue to the export_fig web page (link at the top).

08 Mar 2012 Yuri Kotliarov

Oliver, I have a problem exporting bar-plot to PDF if I set the FaceVertexCData property. The output has no plot, only empty axes.

Here is a code example:
hx = bar(rand(10,1),'hist');
fvcd = zeros(10,3) + 0;
fvcd(1:5,:) = 0.5;
set(hx,'EdgeColor','none','FaceColor','flat','FaceVertexCData', fvcd)
export_fig test -pdf

06 Mar 2012 Jaroslaw Tuszynski

Very useful function. i found it especially useful for creating images for PowerPoint presentations which were small enough to be send by email.

05 Mar 2012 Blake Richards  
04 Mar 2012 Umberto

Wow, this is incredible! Finally the long and arduous journey of finding a function that prints cropped vector quality figures is complete. I would give it 6 stars if I could. Cannot thank you enough man. Fantastic work, much appreciated.

01 Mar 2012 Bijesh

thanks a lot!

25 Feb 2012 Igor  
25 Feb 2012 Kiron

Great work!

24 Feb 2012 Chad Greene

Excellent. This has worked wonders for my PowerPoint presentations.

18 Feb 2012 Wonsang You  
14 Feb 2012 Jinwei Gu  
09 Feb 2012 Kevin Moerman

I've tested this for some patch graphics and pdf export. If I just use: export_fig test.pdf, Then for intersecting patch objects (without transparency)it sometimes places the wrong patch objects in front.

Other than that very nice.

03 Feb 2012 Giorgio  
27 Jan 2012 Ken Campbell

Oliver was extremely helpful when I contacted him with a question. His page
http://sites.google.com/site/oliverwoodford/software/export_fig
also provides many helpful tips.

27 Jan 2012 Oliver Woodford

alexancer: Yes. I don't recommend exporting large patch-based objects to EPS. Better to create a resterized version (e.g. export to PNG) then embed in an EPS file using an external application.

27 Jan 2012 alexancer

One problem is when I export eps file from a surface graph from thousands of data points. The size the exported file is very large, almost 40MB for each.

26 Jan 2012 sunil anandatheertha

wowwww...! Thanks a lot for this great share. Still a beginner here,, :),, and your codes are giving me a lot to learn.

Extremely useful.. Am sharing the links with frnds.. B)

19 Jan 2012 Oliver Woodford

Kemal: MATLAB cannot save transparency using the painters algorithm, so transparency in eps cannot be supported in export_fig either. You can save vector graphics with transparency by exporting to svg (http://www.mathworks.com/matlabcentral/fileexchange/7401), then convert to eps using an external program.

As for the bug, if you want me to look into it please follow my many requests and contact me directly.

19 Jan 2012 Kemal

Needless to say the Matlab functions don't work.

19 Jan 2012 Kemal

There are problems when exporting figures containing two transparent patches (using patch.m and setting 'facealpha' 0.7).

set(gca,'Color','none')
export_fig 'filename.png' -transparent

this results in a correct png-figure, however I need a higher resolution picture than the default. Using the following command

set(gca,'Color','none')
export_fig 'filename.png' -transparent -m2

the picture gets screwed up: weird misalignments in the upper half of the figure.
Is there a fix for this problem? Exporting a figure with transparent patches to png in high quality (if it would work for eps as well I'd be thrilled).

Thanks!

18 Jan 2012 Zoe Zhang  
17 Jan 2012 Petteri T  
12 Jan 2012 Darren Price

Why on earth is this not part of matlab as default? Sort it out Mathworks people need this type of thing!

12 Jan 2012 Ingo  
01 Jan 2012 Ioannis Filippidis

Works perfectly, thanks! Very powerful in combination with LaTeX annotated axes, title and legend, with export to PDF for use in XeTeX. More direct than other methods (e.g. laprint, PStricks, METAPOST, TikZ exports).

26 Dec 2011 Renwen Lin

v good!

23 Dec 2011 Xin

Very useful package to export beautiful figures.

20 Dec 2011 Nathan Tomlin  
09 Dec 2011 Sebastien PARIS  
08 Dec 2011 Ankur Pawar

Very useful function.

07 Dec 2011 Chris

This is great.

Does anyone know how I can add bookmarks to a multi-page pdf file?

Thanks

07 Dec 2011 Rene

You are one of my favourite persons now. THANK YOU!!

07 Dec 2011 Rene  
06 Dec 2011 John Colby

This is my favorite FileExchange submission. Period. I've been using it for over a year, and can't imagine going back to the old way. Thanks, Oliver!

29 Nov 2011 owr  
27 Nov 2011 Daniel

Hey Oliver,
thanks for that impressive tool. One problem/question:
I got a square axes in a 16:10 figure. Although I use
set(gcf, 'InvertHardcopy', 'off', 'Color', 'black')
the figure background (not axes bg) and legend texts are getting inverted (also with print()). Is there any way to prevent that? I also used -transparent, but without success.

Thanks, Daniel

24 Nov 2011 Anuj  
14 Nov 2011 pietro

This function is really great, but the eps quality isn't good as the pdf one. Do you have any suggestion?

09 Nov 2011 Cameron Sparr  
03 Nov 2011 Son Hua  
31 Oct 2011 Sam Hallman

I use export_fig all the time and I love it. I've made a lot of wonderful figures thanks to this tool. The web documentation is excellent.

31 Oct 2011 Sam Hallman  
27 Oct 2011 Onkar Singh Gujral

very good

07 Oct 2011 Felix Zoergiebel

I have problems with calling ghostscript (and also pdf2ps) from MATLAB R2011b on OS X 10.6.8. system('/opt/local/bin/gs') gives me this error:

dyld: Library not loaded: /opt/local/lib/libfreetype.6.dylib
Referenced from: /opt/local/lib/libfontconfig.1.dylib
Reason: Incompatible library version: libfontconfig.1.dylib requires version 14.0.0 or later, but libfreetype.6.dylib provides version 10.0.0
/opt/local/bin/gs: Trace/breakpoint trap

I fixed the problem by deleting MATLABs DYLD_PATH_LIBRARY variable before calling ghostscript in ghostscript.m:

[varargout{1:nargout}] = system(sprintf('export DYLD_LIBRARY_PATH=""; /opt/local/bin/gs %s', cmd));

Same should work for pdf2ps.m.

This problem does not exist on MATLAB 7.4, since there is no libfreetype.6.dylib in the MATLAB installation. Hope that this little report helps somebody else.

22 Sep 2011 Erika  
19 Sep 2011 Oliver Woodford

Shaun: Thanks. I understand a big change to the way MATLAB handles graphics is coming at some point. When it does I expect export_fig will break in many ways. For now you can disable the warnings.

19 Sep 2011 Shaun

Heads up, set(gcf,'color','none') is going away. I am getting warnings..

18 Sep 2011 Oliver Woodford

apañero: Use the -r180 option to set the dpi in the image file correctly (Otherwise how is export_fig supposed to know the dpi? That information isn't stored anywhere in the figure.). Then set the image size so you get the desired output resolution (size of image in pixels). In your case the image size on screen should be 7cm x 7cm.

17 Sep 2011 apañero

There is a problem if you want to keep the same resolution and document size as the original image.

With a 180dpi image and 7 x 7cm size
export_fig image -tif -native
Image exported is 96dpi and 13 x 13cm size (same overall resolution but different dimensions)

If I use -r180
Image exported is 180dpi but 13 x 13cm and double pixel size (again, same overall resulution but image dimensions are wrong).

export_fig image -tif -native

14 Sep 2011 Oliver Woodford

Ole: Export_fig doesn't support embedding tiff previews in eps files, sadly. It's probably possible to do with an external application, and if it has a command line interface you could write a MATLAB wrapper for it.

13 Sep 2011 Ole

This code is of great help! Can anyone say whether or how tiff previews/thumbnails can be included into eps files?

02 Sep 2011 David Wang  
23 Aug 2011 Peter

Be warned, you *will* need to tune image parameters to make your image file consistent with the results from saveas.

23 Aug 2011 Peter

Works excellently. Found out how to make CMYK tiffs for publication. Follow this code:

figure('InvertHardcopy','off','Color',[1 1 1]); % Force the background to be white
plot(x, y);
export_fig([filepath filename 'full'], '-tif', '-cmyk', '-r300'); % For CMYK 300 DPI tiff images

22 Aug 2011 Oliver Woodford

I'm afraid I won't be responding to requests for help in this comments section from now on. The help text and web page are more than detailed enough. Bug reports can be emailed directly to me.

22 Aug 2011 Martin

Hi
This is a very very useful function. But I have one problem. I am not able to get the same screen resolution while exporting quiver plots. I export quiver plots to .tiff files and then I open it in Imagej. But the arrows appear very blurry as I zoom in. I tried the following:

export_fig test.tiff -m2 -r 250

It would be great if you can help me with this.

Thanks
Sundar

09 Aug 2011 Oliver Woodford

Patrick: A clean install of R2011a and export_fig on a 32-bit XP machine yielded a cropped, correctly sized figure for me just now. Sorry not to be more help!

08 Aug 2011 Patrick Maletinsky

Oliver: Thanks much for checking! I just repeated what you did (plot(rand(3)); export_fig test.pdf;) and sure enough, the output-pdf contains the figure with the (standard) gray background on a letter-sized white background.
Since things work out on your installation it might have something to do with my Matlab settings/preferences (?). I didn't set anything special though and also checked on a couple of other machines of colleagues of mine and the scheme seems consistent: R2011a yields letter-sized outputs and all earlier installations do what I tell them to do.

If anybody knows a solution to this problem, I would greatly appreciate. For now, I just run export_fig on older versions of Matlab only ;-)

Again, thanks for this great script in any case, Oliver!!!

P.S.: This was all on Windows XP 32-bit machines.

05 Aug 2011 Jiaqi  
04 Aug 2011 weijie

You save me thesis!

03 Aug 2011 Oliver Woodford

Patrick: I just installed R2011a on a Vista 32-bit machine and ran
plot(rand(3));
export_fig test.pdf;
It worked as expected.

02 Aug 2011 Patrick Maletinsky

Great script - thanks a lot Oliver!

I recently upgraded from Matlab R2009a to R2011a, which caused a problem with export_fig: after the upgrade, figures exported to .pdf (and/or .eps) have a fixed paper-size of US legal (i.e. typically a lot of white space around my figures). I can't find a way to alter the paper size of my exported figures in Matlab now. When I ran export_fig on Matlab R2009a, the paper-size after exporting with export_fig used to be set by the original figure size. Any ideas how I can get back to these settings?

02 Aug 2011 Patrick Maletinsky  
29 Jul 2011 Sébastien  
28 Jul 2011 Jie

Hi, Oliver, thank you so much for your kind help. The zbuffer renderer works for me. However, I still prefer the EPS output than BMP (it blurs when zoom out or zoom in). As what you said, the white tin network did have different appearances in different applications.

Thank you once again for your kind help.

28 Jul 2011 Oliver Woodford

Jie: Yes, the lines should not be visible in printed figures. Also, try the zbuffer renderer if opengl fails.

28 Jul 2011 Jie

Hi, Oliver, thank you for your swift reply. You know, Google is fighting against with the Chinese government, and I can not see the examples and explanations listed in google site.

What you mean is that the paper-printed figure will not show such tin network? However, when I try to save the bmp and jpg format, I got following error:
setting PBuffer for OpenGL printing: invalid drawable.

Interestingly, I did save jpg file several days before. I do not know why I can not save bmp now.

28 Jul 2011 Oliver Woodford

Jie: I explain the reason for this on the examples webpage. It's your PDF reader at fault, but it means that 3D surfaces are better exported as bitmaps.

27 Jul 2011 Jie

Hi, Oliver, the export_fig is really a great tool which helps a lot to my paper. Thank you.

But, I got a problem when I want to export a 3D surface produced by 'mesh' or 'surf'. Although the output in the figure window of Matlab is normal, the exported figure are covered with white tin network, which is especially evident for gray surface.

Actually, you can find the white tin network on the icon of export_fig at the top of this webpage (the nice color surface produced by this tool is covered with white tin network).

This problem is deriving me crazy in recent days. I tried to change various line properties, however, it never works.

22 Jul 2011 Oliver Woodford

Brad: You can use -painters and -r200. If it doesn't do what you expect then contact me directly. Also, just put the files on your MATLAB path to avoid moving them to your current directory - that is standard and nothing to do with export_fig, though.

22 Jul 2011 Brad

This function is fantastic. Whats more, is that it can be incorporated into my functions, so that I can save multiple plots and figures in glorious high resolution. I love it and its so easy to use!

However, I've been copying all the export_fig files located in the export_fig folder to current working directory (which changes often). This works, but I don't want to do it everytime I start working in a new directory and I want to make figures.

Is there a way to put export_fig in its own folder (perhaps C:/Program Files/Export Fig/export_fig) and call it from my current directory without changing back and forth to that directory? Also, I'd like to use options like -painters and -r200.

Thanks Oliver!

21 Jul 2011 Oliver Woodford

Eli: Yes, -painters works on all systems. If you have a specific problem you should contact me directly.

21 Jul 2011 Eli

Thanks Oliver. I am referring to the size of the image (in Kb). If you have many pictures in your file, the document size grows quickly and cannot be submitted. I already tried -q30 etc, -r, it has no effect. The gs command with options in linux can reduce the size (not so nice), but I want to do everything in export_fig. I guess I have to re-program my plot.

I would like to thank you for this code. It has served me good in past weeks !

Suggestion: put set(gcf, 'Color', 'w') in default. It scares off newcomers to see those, often unwanted, margins.

Is -painters option supposed to work on pdf/eps files on any system?

21 Jul 2011 Oliver Woodford

Eli: Are you refering to file size or paper size? File size can be changed using the -qXX option, e.g. -q50, though it only affects the images in files. If paper size, change the figure size.

If you want me to assist you with errors then I suggest you follow the instructions at the end of the description.

21 Jul 2011 Eli

Great software.

How do you control the size of the output PDF or EPS? I want to reduce the size.

In addition, the -painters option does not work for me, in pdf/eps files. I tried it on various linux and win systems.

20 Jul 2011 Dan K

Oliver,
Thanks for the response... Following your suggestion, I found IMCLIPBOARD (http://www.mathworks.com/matlabcentral/fileexchange/28708-imclipboard) which does just that. Now if I can just find one that outputs to clipboard in vector format.
Dan

19 Jul 2011 Oliver Woodford

Dan: No, there isn't. However, you can output the image as an array, so if you find a way of copying an array to the clipboard as an image you're there.

19 Jul 2011 Dan K

Hi Oliver,
Very nice. One question: I am also fighting with the whitespace outside of copied images. Your cropping seems to do the job nicely. Is there a way to use export_fig to export to the clipboard?
Thanks,
Dan

18 Jul 2011 Oliver Woodford

pvans: You can control the amount of whitespace around an axes by setting the axes' position and using export_fig's -nocrop option.

17 Jul 2011 Austin

Thanks for this.

Mathworks, it's ridiculous that I have to resort to third-party packages to programmatically export my figures. Every time I come across some problem like this it moves me closer and closer to doing all my development with numpy/scipy.

14 Jul 2011 pvans

Hi Oliver,

I would like to save an figure with both

1) an image object inside of it saved at native resolution

2) control over the size of the whitespace outside of that image's axes, in pixels.

Your '-native' option works well for 1), but it seems that in order to accomplish 2) simultaneously, I need to resize the figure without resizing the image. I can do this by setting the image axes 'Units' property to 'Pixels' (instead of the default 'Normalized'), but that change seems to make export_fig work incorrectly. Is there a way to do this with your program?

29 Jun 2011 Emily  
20 Jun 2011 Sherif

Very useful. Thank you.

19 Jun 2011 Céldor

@farzad
In EPS files which I export my figures to, all fonts are changed to different ones. Arial is changed to Helvetica, Arial Narrow is changed to Courier, etc.

13 Jun 2011 Oliver Woodford

Farzad: export_fig has the same font issue as print, as described on my usage and examples web page (link in description above).

11 Jun 2011 farzad

to Zbigniew:
What do you mean by wrong font? isnt it the original font you see before exporting?! It exports the figure as the way you see on the screen. If you want another font you have to change it before using export_fig command.

10 Jun 2011 Céldor

Hi there,

This is brilliant function. It helped me to export figures properly to eps. The only thing is that it still substitutes and exports a figure with wrong fonts.

09 Jun 2011 A

This is the most wonderful program! Thank you :)

07 Jun 2011 Oliver Woodford

Farzad: As you say, export_fig saves the figure as it appears on screen, and you can have a landscape-shaped figure on a portrait-oriented display, no problem.

07 Jun 2011 farzad

Hi Oliver,

This might not be a good question but if you change your display to portrait, is it then possible to save figures in landscape? I guess not since it is said that the figure is saved exactly like it is on the screen.

29 May 2011 Shiguo  
28 May 2011 nsbd  
18 May 2011 farzad  
17 May 2011 Matthijs Klomp  
17 May 2011 farzad

Ah, I made a mistake in that. Thanks for correcting me Oliver. export_fig is really great. Although it doesn't need to mention. 908 downloads just in the last 30 days!!!

17 May 2011 Oliver Woodford

farzad: MATLAB has to ways of passing variables to functions. Withough brackets, every input is considered to be a string. With brackets, you need to specify what is a string and what isn't using ''. This is completely standard. So in your case do:
export_fig(sprintf('plot%d.png', a), '-a1');

16 May 2011 farzad

Hi Oliver
I have a question regarding the export_fig use in a for loop. In the examples, you gave this format for it:

export_fig(sprintf('plot%d.png', a));

what if I want to use additional arguments as well such as disabling the anti-aliasing which originally is:
export_fig plot.png -a1
I tried different formats to pass the value of 'a' parameter to export_fig in the loop but I failed. Shouldnt it be like this:
export_fig(sprintf('plot%d.png', i),a);
where a (anti-aliasing value) is the second input argument to export_fig ?!

I appreciate your great work it.

29 Apr 2011 Dan

Thank you Oliver. I honestly did not notice it. The interface of the File Exchange has changed quite a bit recently and yours is the first file I download. The clarity of the tag "Download All" could be disputed though.

28 Apr 2011 Oliver Woodford

Dan: There is a large blue "Download All" button at the top right of the page. Did you try that? It worked for me.

28 Apr 2011 Dan

New file exchange interface is just not working. No "download" option displayed and "Watch this File" sends you in a loop between the current page and the "Watchlist" without actually showing the file.

Any suggestions?

08 Apr 2011 Liang Zhan

actually it's Walter Roberson refer me to use your function, excellent, it solve me a big problem, appreciate for your code!!!

08 Apr 2011 Martin  
06 Apr 2011 farzad

I didnt know about drawnow. It works better with graphics and I learned a new command. Thank you very much Oliver.
Success

06 Apr 2011 farzad

Thanks Oliver. I'll try to replace maximize with something else.

06 Apr 2011 Oliver Woodford

Farzad: However, a solution is to call drawnow just before export_fig.

06 Apr 2011 Oliver Woodford

Farzad: This is an issue with maximize, and not export_fig.

06 Apr 2011 farzad

Hi
Thanks for sharing this very useful file.
I have a problem with using export_fig with maximize. May be someone can help. When I use maximize I have to add pause (at least 0.5 sec) before export_fig otherwise it saves the small size version. Here is the order of commands:
h = figure;
maximize(h);
plot ...
export_fig test.bmp -m2

------------------------
R2009b on Win 7, 32 bit

25 Mar 2011 Martin  
16 Mar 2011 Katharina Schaefer

Hi Oliver, thanks a lot for a great script. I am a mac user (os x 10.6) and had some trouble with ghostscript. On this website http://www.linuxfoundation.org/collaborate/workgroups/openprinting/macosx/hpijs you can download GPL Ghostscript (dmg file). This worked for me.

15 Mar 2011 Reza

Great function!

When working with images, that would be great to export the lines, texts, legend, etc. in a vector format and the images in a pixel format (ideally both in one pdf file). You might know that there has been some work done in the original exportfig http://www.mathworks.com/company/newsletters/digest/december00/export.html

I think it will be a great feature!

05 Mar 2011 Oliver Woodford

Meggy: Make sure that you have installed ghostcript (not the ghostscript.m MATLAB function) as per the instructions, then select the folder which contains the ghostscript program when prompted. If you have any more problems please contact me directly, as requested several times on this page already.

22 Feb 2011 Oleg Komarov

I'll start using matlab graphics thanks to your function!

20 Feb 2011 Oliver Woodford

Bogdan: This sort of issue is best emailed to me as a minimal working example.

20 Feb 2011 Bogdan

Hi Oliver,

when I create a pdf file and include it in Latex the blue color get washed in the Latex document. However, it is okay in the created pdf itself. Do you have any idea why, as it looks really bad. Other included pdfs created with the print command do not have this issue.

15 Feb 2011 Oliver Woodford

Reinhard: Thank you. That could be very useful info for some people out there.

15 Feb 2011 Reinhard

FYI: I've just tried creating temporary PDF files using export_fig, and then appending them in a single go using ghostscript. It's much faster that way. Ghostscript obviously optimizes the call if it receives all the file names to append simultaneously.

15 Feb 2011 Oliver Woodford

ImageAnalyst: It demonstrates that you can export figures with transparency information (as one is visible through the other). Probably not very intuitive, though.

15 Feb 2011 Image Analyst

I'm not sure I understand your screenshot. Why the double images superimposed?

15 Feb 2011 Oliver Woodford

Reinhard: No, this isn't something I've investigated. One possibility is that the slowness comes from export_fig copying the file before appending to it, for error recovery reasons. You could take this step out of eps2pdf.m and see what happens. Otherwise it's down to ghostscript, which I have no control over.

15 Feb 2011 Reinhard

Thanks Oliver, we've been using your code for a while and especially use the PDF export function. One thing that we have noticed is that if you append a lot (30+) of plots to the same PDF the process becomes much slower as the PDF gets bigger. Do you know what causes this?

15 Feb 2011 Reinhard  
14 Feb 2011 Elsa Birch

Many thanks!

06 Feb 2011 Joseph LIM  
03 Feb 2011 Rossella

This is a really useful and well written funnction. Thanks a lot!

03 Feb 2011 Ask Svane  
03 Feb 2011 Ask Svane

Great work!

25 Jan 2011 Tobias Lamour

Hi Oliver,
Thanks for your incredible work here! You saved me lots of time already you triple the value of Matlab without a shadow of a doubt.
Please carry on as you did.
Cheers, Tobi

30 Nov 2010 mathworks2011  
25 Nov 2010 Julia

Dear Oliver,

thanks for saving my (publication) life.

Julia

18 Nov 2010 Oliver Woodford

Craig: Nice observation. Done.

15 Nov 2010 Craig

Thanks for the response. It has occured to me that the resolution can be set relative to native by just resizing the image prior to display then using the -native switch. Rather than modifying the function, perhaps add a note to your website for people who are slow on the uptake like me?

Thanks again, Craig.

15 Nov 2010 Oliver Woodford

Craig: Intermediate images can be larger than the output image if antialiasing is used, so the warning is correct. Your suggestion of an additional resolution option has been noted - thanks.

15 Nov 2010 Craig

Great function(s) - thanks Oliver. It works very well in concert with 'maximize.m'.

Like so many others I'm at a loss to understand why such functionality isn't built-in to MATLAB. I had reached the point of saving my images as MATLAB 'fig' format and copying and pasting into other documents to try to preserve some quality. I have one small, almost insignificant, suggestion:

Could a additional resolution option be included so that resolution can be specified as a percentage of 'native' rather than only relative to the size on screen? Is there a simple way to do this already using the -r switch?

I've also noticed that MATLAB (Win7 64-bit R2010b) produces a scary warning "Warning: print2array generating a 185.1M pixel image. This could be slow and might also cause memory problems." when in fact the image size is one-tenth that with -m set to 10. It's not important but had me worried until I realised it was bunkum.

Thanks again,
Craig.

03 Nov 2010 Matthijs Klomp

I have used print_pdf for all my publications.

29 Oct 2010 Nick Fyson

Excellent function, makes it easy to produce high quality figures. (Normally look significantly better than in the figure window itself.) Never had a single problem with it.

29 Oct 2010 Oliver Woodford

Monique: The cropping works fine on my system with the figures you give. No-one else has reported this problem either, so I would say that the autocropping does work, and that your comment is misleading to other users. Read on if you would like me to investigate your specific problem further.

Everyone: As I've stated twice on this page already, please do email me (use the "Contact Author link on my author page) when you have a problem (assuming you've checked everywhere and can't find a solution), rather than place it here. I'll respond quicker, be able to request figures and results, and also people finding the function won't think it never works!

28 Oct 2010 Monique Messié

Very useful function even though I'm far from having explored all the possibilities.
One question: when saving a figure with a transparent background, the autocrop doesn't work. Any reason for that? any way to still get autocrop?
Example:
figure, plot(1:10), set(gcf,'Color','w'), set(gca, 'color', 'w','XLim',[0 20]);, axis off, export_fig test % (autocrop)
figure, plot(1:10), set(gcf,'Color','none'), set(gca, 'color', 'none','XLim',[0 20]);, axis off, export_fig test2 % (doesn't autocrop)
Thanks!

27 Oct 2010 David Lloyd

Superb function and documentation. You deserve a big fat check from Mathworks for doing something long overdue. In the mean time please accept my grateful thanks :)

16 Oct 2010 Vinesh Rajpaul

Good documentation, easy to use, and does the job very well! Thanks!

16 Oct 2010 Vinesh Rajpaul  
24 Aug 2010 Matthew Arthington  
16 Aug 2010 Mark  
09 Aug 2010 Joseph  
04 Aug 2010 Joachim Schlosser

A great script. Along with the hints in article http://blogs.mathworks.com/loren/2007/12/11/making-pretty-graphs/ this makes pretty nice graphics!

09 Jun 2010 Oliver Woodford

Dan: Unfortunately this can't be avoided. The painters renderer used for vector graphics doesn't support transparency. For more details see here:
http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/f3-84337.html#f3-102410

09 Jun 2010 Dan

Very nice script, I use it all the time.

Just one thing, when saving to a .pdf it seems to mess up transparent elements on the the plot and make them opaque.

Is there a way to remedy this?

Cheers!

03 Jun 2010 Daniel

I was wrong, it does work to include the path in the file name. I just can't use a '~' as a short cut to my home directory. At least not with a Mac. Using the full path works for all formats, and the '~' works for everything expect pdf and eps.

Oliver, thanks for your help troubleshooting this for me!

03 Jun 2010 Daniel

this program is great. I have tried several hacks over the years to do something similar, but not worked this clean.

When specifying a path in the file name it works for all formats except pdf and eps. These will only save to the current directory. Is there a way to specify the path in the call? Currently I just cd to the desired directory and then cd back to where I was.

Thanks for the work and for sharing.

03 Jun 2010 Daniel  
25 May 2010 Philip Valencia

Top job Oliver - great utility with a tonne of functionality.
The -painters option is great. I can render a graph from the command line with transparent axis and background and save it onto my desktop (with geektool). It looks so awesome and it wouldn't be possible without these scripts.

18 May 2010 Oliver Woodford

Royi: This will generate two images, one with anti-aliasing and one without -
export_fig aa.png
export_fig no_aa.png -a1
The anti-aliasing option can be used with any other combination of options. Note that the anti-aliasing settings only affect bitmap outputs. They make no difference to vector outputs such as pdf and eps files.

17 May 2010 Royi Avital

You need to clarify the syntax a bit more (I don't understand how to turn Anti Aliasing off, Triad -a1 with no difference, I guess I don't write the syntax how it should be).
Adding some examples for usages of the Syntax would be great!

22 Apr 2010 Oliver Woodford

Jared: Fonts should be embedded in exported pdfs by default, and also in eps files (the latter depending on what pdftops executable you have on your system). You need to import a figure into Myriad Pro before exporting from it - I suggest you ask the newsgroup if you need help with this.

21 Apr 2010 Jared

How does one export with embedded fonts? For instance, can one export using Myriad Pro?

13 Apr 2010 Adam A

Very useful, thanks.

12 Apr 2010 Sylvain Fa

Very good function. I am using it for a while now without any problem. I have just noticed that when a figure contain a:
"text(...,'interpreter','latex')" then the function print2eps does not set the boundingbox properly or at least the figure is not cropped when using eps2pdf.

A closer look at this showed that when the latex interpreter is used, the obtained eps file (with the MATLAB print function) contained font information. This might interfer somehow. Any idea how to solve this issue?

10 Apr 2010 Glenn Fulford  
10 Apr 2010 shuangou ren

very useful. simpler use with respect to the laprint

09 Apr 2010 Glenn Fulford  
09 Apr 2010 Shai Sabbah

Oliver: Thank you very much.
Finally I can produce nice figures with Matlab.
Shai

09 Apr 2010 Oliver Woodford

Shai: The line style problem can be fixed by specifying the painters algorithm, using the -painters option. Note you need ghostscript installed for this to work.

09 Apr 2010 Shai Sabbah

Great program.

However, I’ve encounter a small difficulty.
I’m trying to export a B&W figure that includes solid, dashed, and dotted lines at a resolution of 350 dpi in tif format. However, in the tif image, dashed lines look like dotted lines, and the dotted lines look like solid gray lines.

I’ve tried all the four anti-aliasing levels.

Is there a way to export in high resolution tif format while keeping the appearance of the lines similar to the original?

Thanks a lot,
Shai

09 Apr 2010 Roland  
20 Mar 2010 Michael Johnston

Extremely useful.

03 Mar 2010 Oliver Woodford

In response to comments by Muhammad and xtofe xtofe I've added the -native and -r<val> options respectively.

Viktor: I don't have or use Simulink, unfortunately, so can't address your issue. Simulink support was never claimed, though, and I hope the function does everything it says on the tin.

24 Feb 2010 viktor

Hi Oliver,

Your file works great but is there a way to apply it to simulink systems? you can print a picture of your model but cropping is very hard.

Viktor

18 Feb 2010 Oliver Woodford

Jonas:
I convert from eps to pdf then back to eps because I know how to set the quality of bitmap compression and how to embed fonts when saving to pdf through ghostscript, but not when saving to eps. My hack is therefore to save as a pdf to get these things right, then use software which converts a pdf to eps without changing anything in those respects.

If anyone knows of a more direct approach please let me know.

16 Feb 2010 Jonas

Very useful program!

1) When you print to .eps, you print to .eps, then convert to .pdf, then back to .eps. Why?

2) On OS X, the uigetdir file dialog does not show the title. Thus, when the user is asked to provide the path to pdftops, it is not clear at all what is going on. I suggest adding the following before line 60 of pdftops.m:
if ismac
wh = warndlg('pdftops not found. Please locate the program, or install xpdf-tools from http://users.phg-online.de/tk/MOSXS/.');
uiwait(wh)
end

29 Jan 2010 Jean-Baptiste Carré  
26 Jan 2010 Oliver Woodford

xtofe xtofe:
Set the magnification as follows -
dpi = 300;
mag = dpi / get(0, 'ScreenPixelsPerInch');
export_fig('name.png', sprintf('-m%g', mag));

26 Jan 2010 xtofe xtofe

very useful it is indeed.

How the resolution of the final file could be changed?
e.g., 300dpi, 400dpi, etc.

Any ideas??

13 Jan 2010 Madhusudhan

Very useful fix for missing functionality within Matlab.

10 Jan 2010 Muhammad

hi again,

thanks for a very helpful hint,i tried using various value of magnification and anti-aliasing until i get the perfect pair to get the native resolution.

09 Jan 2010 Oliver Woodford

Muhammad: This depends on the size of the on screen figure, and the magnification you're applying - you can change these two things to get the output you want. However, it is rarely a good idea to save an image at native resolution by exporting a figure containing the image. I suggest you post what you are trying to do to the newsgroup and ask for suggestions of alternative approaches.

09 Jan 2010 Muhammad

I noticed the image (.jpg) produced doesn't have the same size (eg. 600 x 800) with the input image.how do I set the size to be the same?

07 Jan 2010 Muhammad

yep,it worked well.thanks again

06 Jan 2010 Oliver Woodford

Call export_fig using the functional form to have functional and numerical input arguments, e.g.:
export_fig(figure_handle, sprintf('directory/name%d.jpg', n), '-a2', '-painters');

06 Jan 2010 Muhammad

Hello and good day,
thanks for a great submission.
I'd like to know how do I save a figure along with the directory path,like the one i figured with imwrite function
imwrite(img,sprintf(directory/name.jpg))

30 Nov 2009 Oliver Woodford

For improved rendering of dashed and dotted lines in bitmap outputs (especially at higher magnifications) you can now use the painters renderer:
export_fig test.png -painters
However, see the help text for notes on the impact of using different renderers.

30 Nov 2009 Yvonne Haesevoets

Thanks for the last version, which solves the line-style issue!

29 Nov 2009 Xuezhong Wang  
23 Nov 2009 Oliver Woodford

A useful aspect of export_fig is that it can output the rasterized figure as an image array. For example, you can use this output to save the figure in grayscale, or with a specific resolution (pixels/inch value).

22 Nov 2009 Yvonne Haesevoets

...and how do you preserve the line style in tiff files e.g.? Thanks again!

22 Nov 2009 Yvonne Haesevoets

Absolutely awesome!! If only I had found this sooner!! Thanks for sharing!
How can I increase the resolution? The -m option increases the file size, not the resolution.

20 Nov 2009 Bob

Oliver, thanks very much but something is funny. If I have the property editor open for the original figure the color is white. I run the set commands and the color is none. I then use export_fig and the color goes back to white (as seen in the Property Manager), and the figure has a white background (export_fig foo.png -pdf; OS X 10.6.2, 2009b). Same white background on the pdf and the png.

20 Nov 2009 Oliver Woodford

Bob:
set(gcf, 'color', 'none'); % Set the figure background to transparent
set(gca, 'color', 'none'); % Set the axes background to transparent

20 Nov 2009 Bob

Wish I had found this great script sooner!

Can someone tell me how to set the color property to 'none'. If you set edit figure and then use the property editor you only get an option for color (e.g. a palette), you can't type in 'none'. I'm missing something obvious here, can someone please help me with this.

20 Nov 2009 Bob  
13 Nov 2009 Keely Willis

My graphics driver was out of date. Since I updated the driver, everything work perfectly. Thanks!

12 Nov 2009 Oliver Woodford

A reminder for everyone: As I say in the description, please do email me (use the "Contact Author link on my author page) when you have a problem, rather than place it here. I'll respond quicker, and also people finding the function won't think it never works!

12 Nov 2009 Keely Willis

I'm having trouble printing to png format, the figures come out completely black. I'm using MATLAB version 2008b. The command I'm using is "export_fig filename -png".

Thanks for any advice.

11 Nov 2009 Clark Richards

Great script. It's driven me nuts for a long time that outputting to pdf in Matlab is a headache.

It would be useful if there was an 'append' option for the pdf output. I don't always want to append to the end of a file, often I just want to update a figure and have it overwrite whatever was already there.

26 Oct 2009 Oliver Woodford

Michael: MATLAB's print often does funny things to a plot, such as changing the number of tick marks, when you export it, and I don't know how to avoid it. Export_fig uses print, and therefore unfortunately suffers from the same problem.

20 Oct 2009 Michael Kitz

I wanted to use this tool to save a jpg with the borders cropped. Now I realized that the axes settings were changed during export.
I was using a figure with three subplots, two graphs and an image.
The plots were displaying 7000 data points in a customized scale using the whole axes area. Matlab's autoscale uses 8000 points and so did the export function.
Is there a way to avoid the autoscale?

27 Sep 2009 Francesco Montorsi  
22 Sep 2009 Oliver Woodford

m g: The figure you wish to export must be open. You cannot specify it by the filename. The filename is that of the output file, not the input file.

Erica: The filename should be a string. Just like any other MATLAB function, you can call export_fig using parentheses around the input arguments, or not, in which case the inputs are interpreted as strings; i.e. if one of the inputs is not a string then you must use parentheses. The outputs are not the same as those used by print. Type
help export_fig
for a full description of usage.

18 Sep 2009 Erica Alston

Hi

What is the calling sequence for using this function? should the filename be in parentheses? are the output formats the same as used by matlap e.g. -depsc?

Many thanks!

14 Sep 2009 m g

I am unable to use export_fig on my linux machine
i am using the command
export_fig f.fig -eps
and i get the following error:
'No Figure to Print"
and a Warning /tmp/tmp<long string>.eps not found

please help.
thanks,

31 Jul 2009 Annette

I'm trying to use this function with Matlab r2007b on a Mac (OS 10.5), and I get the error:

??? Error using ==> rdivide
Number of array dimensions must match for binary array op.

Error in ==> export_fig at 143
A = uint8(B ./ A(:,:,[1 1 1]));

Any insight?

Cheers!

22 Jul 2009 Jason Mar

Great function! It saves me a lot of time, thanks!
Wish I could disable cropping more easily though.

14 Jul 2009 cartonn

how do you export the image with a greater value of dpi?
-r600 does not work

08 Jul 2009 Sebastiaan  
07 Jul 2009 Johannes Korsawe

Really nice.
I still have a problem using uipanels (guis):

If i create a plot and a colorbar, the colorbar will not be printed in the result.

Is it possible to enable for a search for colorbars? I tried to adopt your code but failed in copying the correct stuctures.

To say it with Stefan: Can you fix/enable that?

03 Jul 2009 Gabriel Akira Schreiber  
02 Jul 2009 Gabriel Akira Schreiber  
29 Jun 2009 Daisy Fan

Nice!

How can I get a high resolution eps, e.g., >300dpi? Matlab's documentation says to use the -r option, e.g.,
print -deps -r300 myfile
but it actually doesn't work. When I look at the produced eps in a software such as Adobe Photoshop the resolution is just 72dpi. Thanks for you input!

03 Jun 2009 Stefan

Great job!

But still one bug: Exporting does not work if axes is child of uipanel. Seems to be some problem when using cobyobj
Can you fix that?

28 May 2009 wei feng

Great work! You sir saved me a LOT of time.

I've been using your print_eps function for a while and found this today. However, I have a problem with converting images to eps format that has been bugging me. For example, I have two images in a matlab figure. On both images I have used the "plot" function to plot some lines on the images. The plotted lines are gray in color. When I export them into eps format, the lines on the first image would remain gray. But the lines on the second image would change to black. The same thing happens when I have more than two images with plotted lines, in which case all the plotted lines except in the first image will turn black. I was wondering if you can shed some light on this?

Thanks a lot.

28 May 2009 Edgar Guevara Codina

Great job!
Finally I can get publication-quality graphs in a simple way.
Thanks Oliver for making it easier than ever before.

21 Apr 2009 Christian Dorion

Great piece of work, thanks.

A minor thing though... Under my installation, the private/ghostscript.m function had a minor bug that resulted in the whole function being whipped out and replaced by solely the 'gs' path. Just in case it happens to anyone else, here is a simple patch:

--- MY/private/ghostscript.m
+++ ONLINE/private/ghostscript.m
@@ -103,9 +103,8 @@
fstrm = fread(fh, '*char')';
fclose(fh);
% Find the path
-first_sec = regexp(fstrm, '[\n\r]*function path = current_gs_path[\n\r]*path = ''', 'end', 'once');
-second_sec = first_sec + regexp(fstrm(first_sec+1:end), ''';[\n\r]*return', 'once');
-assert(~isempty(first_sec) && ~isempty(second_sec));
+first_sec = regexp(fstrm, '[\n\r]function path = current_gs_path[\n\r]path = ''', 'end', 'once');
+second_sec = first_sec + regexp(fstrm(first_sec+1:end), ''';[\n\r]return', 'once');
% Save the file with the path replaced
fh = fopen(fname, 'wt');
fprintf(fh, '%s%s%s', fstrm(1:first_sec), path, fstrm(second_sec:end));

19 Apr 2009 Oliver Woodford

Dan: Currently the only way to change the exported figure size is to change the Matlab figure size before exporting. To get round this, set the paper size options manually within export_fig.

Matt C: Thanks for the great suggestion.

Shameem/Mohammed: I wanted to keep the interface simple, so unfortunately there is no formal way to control file size. Jpeg file size can be changed by varying the quality setting within export_fig. For more options regarding quality/compression, see savefig (also on the FEX).

18 Apr 2009 Mohammed Islam

Hi Oliver,
Thanks soo much for this script. It's of great use for me. So far I haven't had any trouble using it. Just one question, is it possible to use it to control the size of the output file?

Also, thanks to Matt for the addition, Its nice to not replace an existing file and keep adding up additional figues at the bottom. Thats what I wanted to do.

Great job guys. keep it up.

Shameem

17 Apr 2009 Matt C

This suite of exportation options is really great! I used to cook up these functions on my own, but with the frontend you created this is now a lot simpler.

When using it I found that the way you are currently implementing ghostscript will destroy the destination file if it already exists. While this may be the intended implementation, let me offer an alternative that could possibly be as useful to others.

I have edited the 'eps2pdf.m' file to allow for appending additional figures to an already existing .pdf file as follows:
<code>

function eps2pdf(source, dest)
% Construct the options string for ghostscript - create new or append
% additional sheets if the destination exists
if (exist(dest, 'file') == 2)
tmp_nam = tempname;
copyfile(dest, tmp_nam);
options = ['-q -dNOPAUSE -dBATCH -dEPSCrop -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '" "' tmp_nam '" -f "' source '"'];
else
options = ['-q -dNOPAUSE -dBATCH -dEPSCrop -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="' dest '" -f "' source '"'];
end

% Convert to pdf using ghostscript
ghostscript(options);
return

</code>

I hope some of you can find this modification useful!

15 Apr 2009 danny

Hello! How can I use your program to export a MATLAB graph to .eps or .pdf format with size changes ?

Thank you,
dan

Updates
15 Apr 2009

Added ability to export rasterized figure straight to the workspace.

19 Apr 2009

Added ability to append to pdf files, as suggested by Matt C. Corrected some help text.

21 Apr 2009

Incorporated Christian Dorion's patch for updating ghostscript (and also pdftops) path. Fixed bug that didn't correctly detect if pdftops path was valid (due to a MATLAB/Windows bug).

24 Apr 2009

Added ability to compute transparency of patch objects when outputting to png and exporting to workspace.

28 Jun 2009

Fixed bug to allow exporting of axes that are children of uipanels. Thanks to Stefan for pointing out the bug.

21 Jul 2009

Export colorbars associated with subplots when in a uipanel. Thanks to Johannes Korsawe for pointing out the bug.

29 Jul 2009

Added options to disable cropping and set level of anti-aliasing. Added a fix to get round a rendering bug in print (thanks to Johannes Korsawe for pointing it out).

31 Jul 2009

Added option to use zbuffer renderer for bitmaps. This avoids some errors caused by bugs in the opengl renderer.
Fixed bug when exporting greyscale figures with an alphamatte (thanks to Annette for pointing it out).

09 Oct 2009

Added ability to export at any resolution (bitmap outputs only) and also in CMYK colorspace (tiff, pdf, eps only).

12 Nov 2009

Appending to end of pdf files is now off by default, and enabled by the -append option. Suggested by Clark Richards.

12 Nov 2009

Fixed bug that meant -tif lead to jpeg being output instead.

24 Nov 2009

Bug fix (thanks, Andreas Offenhaeuser). Added grayscale option (suggestion thanks to Bob Sica). Added correct resolution for tiff & png (sugestion thanks to Yvonne Haesevoets).

25 Nov 2009

No change to the file, just a correction - I thank Paul Soderlind for suggesting the grayscale output option, not Bob Sica (apologies to you both).

25 Nov 2009

Improved rendering of dashed and dotted lines for bitmap outputs using the -painters algorithm. This overcomes the "shrinking dash" problem mentioned by Yvonne Haesevoets (thanks!).

02 Mar 2010

Added -native option for exporting to bitmap at native resolution of an image. Fixed uigetdir title problem on MAC OS X (thanks to Jonas for the bug report).

03 Mar 2010

Improved accuracy of native resolution feature in some circumstances.

05 Mar 2010

Added ability to vary quality/compression level for jpg, pdf & eps output. Thank you to Fabio Viola for pointing out compression artifacts using the default settings.

08 Apr 2010

Fix to colorbar axes color bug with transparent bitmap export (thanks to Roland Martin for reporting it). Look for ghostcript in default location on 64 bit Windows (thanks to suggestion by Nathan Childress).

13 Apr 2010

Fix for R2006b (possibly even R2007a) and earlier: move embedded fonts after bounding box information. Thanks to Sylvain Fa for reporting the problem.

20 Apr 2010

Fix to bug which caused an error when exporting to transparent bitmap with no colorbar present (introduced 8th April 2010). Thanks to Gracee for reporting it.

25 May 2010

Fixed bug which caused bitmaps to be poorly rendered when using the painters renderer on figures with many patches in. Also added fix to bug reported by Andrew Matthews (thanks!) affecting export in -nodisplay mode.

01 Jun 2010

Added ability to append to tiff. Added link to usage examples web page (thanks to Brett Shoelson for the suggestion).

23 Jun 2010

Isolate axes better in presence of gui objects (thanks to Tammy Threadgill for reporting the issue). Maintain resolution of very small images in vector formats when using lossless compression (thanks to Scott for reporting the issue).

06 Oct 2010

Faster bitmap export using hardcopy. Better error checking for when exporting to non-existent directories (thanks to Aldebaro Klautau for reporting this).

02 Feb 2011

Enable exporting of multiple axes (when a subset of all axes). Don't save user specific paths in .m files that may be version controlled (thanks to Jonas Dorn for the suggestion). Minor bug fixes.

02 Feb 2011

Save user specific paths in a single, hidden directory. Put isolate_axes code in a separate function.

27 Apr 2011

Find 64-bit Ghostscript on Windows (thanks to Paul Durack and Shaun Kline for both reporting this issue). Fix bug in isolate_axes (thanks to Rosella Blatt for reproting this).

28 Apr 2011

Bug fix to ghostscript.m mostly affecting Linux (thanks to Paul Durack for reporting it).

15 Sep 2011

Fix bitmap cropping with painters renderer. Make bitmap outputs exactly the right size. Suppress warnings by setting EraseModes to normal when using opengl or zbuffer renderers (thanks to Pawel Kocieniewski for reporting the issue).

21 Sep 2011

Fix to bug in print2array causing an error when exporting using painters with a white background. Thanks to Tobiar Lamour for reporting it.

14 Nov 2011

Various bug fixes - thanks to Phil Trinh, Mathieu Morlighem and Meelis Lootus for reporting the issues. Also added new -transparent option, and set default anti-aliasing down to -a3.

08 Dec 2011

Allow use of arbitrary fonts with the painters renderer, e.g. in eps and pdf files.

09 Dec 2011

More reliable export of non-standard fonts using painters renderer.

14 Dec 2011

Fix bug affecting export using -painters with spaces in font names. Thanks to David Szwer for reporting the issue.

26 Jan 2012

Improve font swapping behaviour. Thanks to Anna Rafferty and Adam Jackson for reporting issues.

27 Jan 2012

Fix bug when exporting tall figures to bitmap using the painters renderer. Thanks to Ken Campbell for reporting it.

23 Feb 2012

Ensure axes limits are the same on screen and printed.

14 Mar 2012

A bug fix to the previous change, ensuring that axes limits are correctly set. Thanks to Tobias Lamour for reporting the issue.

16 Mar 2012

Fixed a bug to do with copyfig not being available to export_fig. Thanks to Bob Fratantonio for pointing it out.

10 Apr 2012

Make font swapping case insensitive. Fix bug affecting export to bitmap using painters in r2012a (thanks to Andy Matthews for reporting it).

09 May 2012

Add ability to add bookmarks based on figure names into PDFs - thanks to Petr Nechaev for this. Keep tick marks fixed - thanks to Arcelia Arrieta for this.

20 Sep 2012

Fix to bug introduced by R2012b

05 Nov 2012

Bug fix to font swapping in vector formats, fixed paper orientation bug and removed conflict with the path function. Many thanks to Malcolm Hudson, Michael Watts and Michel Slivitzky for reporting those issues respectively.

12 Dec 2012

Allow export of uipanel objects, and improve finding Ghostscript on Windows. Thanks to michael and Ratish Punnoose for highlighting these issues.

22 Mar 2013

Access user strings in text, not binary mode, to avoid errors. Now swap fonts in axes labels when exporting in vector format. Thanks to Christian and Rasmus Ischebeck for pointing out these respective errors.

Contact us