File Exchange

## export_fig

version 3.14 (89.7 KB) by
Exports figures nicely to a number of vector & bitmap formats

Updated 09 Dec 2020

From GitHub

Editor's Note: Popular File 2011 2012 2013 2014 2015 2016 2017 2018

This file was selected as MATLAB Central Pick of the Week

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
- 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, tiff)
- Semi-transparent patch objects supported (png, tiff)
- RGB, CMYK or grayscale output (CMYK only with pdf, eps, tiff)
- Variable image compression, including lossless (pdf, eps, jpg)
- Optional rounded line-caps (pdf, eps)
- 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, while 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, part of the Xpdf package. You can download this from:

Usage examples and tips can be found in the README section at:

A technical description of the various components can be found here:
http://undocumentedmatlab.com/blog/export_fig

This submission was originally created by Oliver Woodford. Yair Altman maintains this utility since Jan 2015.

When reporting bugs, please raise an issue via GitHub: https://github.com/altmany/export_fig/issues
Do not paste the error into the comments below - I will not respond to these.

### Cite As

Yair Altman (2021). export_fig (https://github.com/altmany/export_fig/releases/tag/v3.14), GitHub. Retrieved .

Eric Fritze

Just awesome work and thanks to the good documentation - easy to use. The figures you want to present in the exact format they appear on screen - even with transparent backgorund - only by two lines of code.

J Shin

Mathworks have to buy this code.

Ian Hunter

spectacular work!
I am so thankful you shared it!
There is a small learning curve, but totally worth it.

Emily Schwans

Parsa Omidi

Marcos

It cannot convert to emf format. However, I found an alternative way to force vectorial format (figure('Renderer', 'Painters') ) in some plots

Brian Norsk Jensen

I would prefer a solution, where I didn't have to install Ghostscript on more than 100 computers in order to be able to make multiple page pdfs on them.

Sameh Elgamal

Scott Karbashewski

Fantastic toolbox. Found an issue. Plots using the hfill command in conjunction with "yyaxis left" and "yyaxis right" to create dual axis plots do not save properly, the filled region is blank. But if you manually create a second axes with the y-axis on the other side (i.e. don't use yyaxis to create dual axis plot) it saves without issue.

Pascal Etterli

David Viedma Palomo

Very useful 'toolbox' ! Thanks a lot !
But...may I ask for an 'emf' upgrade? Cropping does not works with this format.

Erik Jäverbrink

J. T. Holmi

Yair, could you add a '-nopromo' parameter to stop weekly consulting promotion messages? For now, it can be stopped by 'setpref('export_fig', 'promo_time', now);' prior to export_fig-calls.

Ameer Hamza

MaHa

Viktor Ferm

Dardag

Tingting Zhang

Teron Nguyen

Wang Jack

J. T. Holmi

Yair, could you add a '-ignoreupdate' parameter to disable automatic "Warning: A newer version of export_fig is available."-messages? I wouldn't want to modify the export_fig code to disable it manually.

Jian Zhou

Has anyone seen this problem? - when the targetted eps file is very large, there is a significant drop of the resolution.

Neuropragmatist

Great submission. Recently updated from 2015 version to 2020 version and noticed a really nice speed increase.

I would agree with Ander that the advertisement messages are at bit odd though. Huge toolboxes that take several people 1000s of hours of work do not include adverts coded into the functions. So by comparison your heated berating of Ander looks quite childish. I have also never seen another FEX submission that included adverts.

Do YOU want adverts in every FEX submission? What about pop-ups? Because you are setting that standard.

In my case the advert kept displaying, even though I think it is only supposed to display once. So I commented out the section within the if loop "if isempty(promo) && ~isdeployed"
I also commented out the section within the for loop "function displayMsg(params, funcName, type, filenameParam)"

zhaichangzhi

Thank you very much. This really solved my problem of saving 3D figures as vector graphics. Since I'm using Windows 10 and Word, I'd like to save my figures as emf format. But I found the size of emf format is more than 20 times larger than svg. And texts in emf figure look not clear in Word. I'm using MATLAB 2019b, Word 2016

Fernando Villaça

Thales

Tiago Dias

Incredible. Thank you. Quite useful for publication purposes.

Mücahid Akbas

Miranda Nixon-Hill

dwi kurniawan

thanks bro

Sama

Mustafa Vardaroglu

Thanks!
I only had an issue with the grey background. For the solution used this: set(0,'DefaultFigureColor','remove')
Credits to the discussion here: https://www.mathworks.com/matlabcentral/answers/58172-figure-export-print-always-has-gray-background-with-png-jpg

FHEPCH92

Amazing Submission.
Nevertheless I'm not able to save with transparency in "svg", "eps" or "pdf" with Matlab R2020a (MacOs).
I'm using the line set(gca,'Color','None') and export_fig('test.svg', '-transparent'), but I obtain a black backgrounded image.

FHEPCH92

A King

Thank you very much! This is really helpful function, and it works also with subplots.

Alison Weber

Yair Altman

@GalWiner, @bstechel - Annotations with EdgeColor='none' work properly in R2019b and R2020a on my Windows 10 machine. If you still see a problem, open a new issue on https://github.com/altmany/export_fig/issues

Olav Queseth

Jacob Spencer

Harry Dymond

@Gal Winer, @bstechel - you have to set LineStyle to 'none' instead of setting its colour to 'none'
@Yair Altman - agreed about your comment to @Ander Biguri. I've been using your export_fig and many hints from undocumented MATLAB for years and I've never paid you a penny.
You could have kept all that info just in your book, and you didn't have to take over the maintenance of this indispensable tool. Many thanks to you for both of these!

Arash Azizi

Yair Altman

@Andar - REALLY?! you get a "Fantastic submission" (one that is the product of many hundreds of workhours) for *FREE* and you complain about a single unobtrusive ad and rate the submission with one star?! I bet you also complain about the ads in free phone apps and computer programs. Perhaps I should send you a free gold-engraved version? would that satisfy your ulterior morality? You selfish, ungrateful so-and-so - you make me sick!

Ander Biguri

Fantastic submission, but the "advertisement" when first run is uncalled for and in my opinion, not moraly OK.

bstechel

@Gal Winer - did you/someone find a solution for the annotation textbox 'EdgeColor' problem?

Tarek Rashwan

Clarke

Gal Winer

Hi Yair, thanks for this function.
i seem to have an issue with an annotation textbox. I set the 'EdgeColor' to 'none' but the PDF output has the border as black.
Is this a known issue and if so, is there a workaround?

thanks,

Gal

Yair Altman

@Jan Vopel - ghostscript.m is part of the export_fig package. You need to install the entire export_fig package, not just append_pdf.m. Then ensure that the folder in which you installed export_fig is in your Matlab path.
@Sebastian, @Arnold, @Patrick - please submit an issue report on https://github.com/altmany/export_fig/issues
@Rohit - export_fig does not copy graphic objects from one figure to another, it exports them to a separate file (PDF/JPG/etc.). Read the documentation for details.
@Jy Han - see https://github.com/altmany/export_fig/issues/285 also, try a newer version of export_fig, since this issue was partially resolved in recent weeks.

Jan Vopel

Hello,
I want to use the append_pdfs.m function, so i installed ghostcript. Nevertheless the error "Unrecognized function or variable 'ghostscript'" occurs. I installed it on another drive than the one my workfile is in. Can anyone help me with this error, maybe you had the same error?

Sebastien

Exporting a figure with many subplots to png, the function had issues with subplot positions: it moved them slightly, but enough to not look good. It came from the print2array function, which mysteriously affected the figure handle fig such that position shifted when later updating figure properties, e.g. when executing set(fig, 'Color', 'w', 'Position', pos);.

I circumvented the issue with the following. Before each print2array execution, do saveas(fig,'tmp'). After each print2array execution, delete(fig); fig = open('tmp.fig'). The draw back is that the handle fig changed, so I just have it as an output of print2array and update it in the parent function.

I would upload my edits, but I don't know how to :-(
Hope this help anyway !

Rohit Deshmukh

Hello,
I am using MATLAB 2019b app designer, I want to use export_fig to copy my Ui Axes to a figure. How this can be done?
will this work- export_fig(app.UiAxes,destination) ??
Thanks

kors Atsua

Works very perfectly. Thanks

Pedro Pedrosa

arnold

I have been looking for a way to keep the output of export_fig as 16bit, but all I can think of is either export to clipboard and then paste as a variable in a workspace or exporting as tmp.tif then imread('tmp.tif') it again and delete after. Both are quite error prone and not nice.
I'd appreciate a better way... like out = export_fig('16bit');

regards

Seung-Goo Kim

S. St.

I have a question about embedded fonts: I would like to use export_fig to create EPS figures without embedding the text into the file (i.e. I want to be able to edit the text afterward). Is this possible? Thanks.

Patrick Hammer

Hello. Are there any limitations to export fig? I'm trying to make images of Q-criterion in fluid mechanics (which I imagine is a dense plot to make) and MATLAB doesn't write it using export fig and seems to get hung up. Thanks!

Yang

jy Han

Hi! I have questions in outputing pdfs using export_fig founction. I am very appretiate if you can answer this questions.The matlab reported errors as follows:
Error: /undefined in .setopacityalpha
Operand stack:
0
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- false 1 %stopped_push 1990 1 3 %oparray_pop 1989 1 3 %oparray_pop 1988 1 3 %oparray_pop --nostringval-- 1977 1 3 %oparray_pop 1833 1 3 %oparray_pop --nostringval-- %errorexec_pop .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval--
Dictionary stack:
--dict:732/1123(ro)(G)-- --dict:0/20(G)-- --dict:131/200(L)--
Current allocation mode is local
Last OS error: Permission denied
Current file position is 9674487
GPL Ghostscript 9.50: Unrecoverable error, exit code 1

Ghostscript error: perhaps C:\Users\23181\AppData\Local\Temp\tpb4f71068_4603_4bb3_8d1f_50d514e8e4de.pdf is open by another application
or maybe you have another gs executable in your system's path

Ghostscript path: D:\Program Files\MATLAB\gs9.50\bin\gswin64c.exe
Ghostscript options: -q -dNOPAUSE -dBATCH -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="C:\Users\23181\AppData\Local\Temp\tpb4f71068_4603_4bb3_8d1f_50d514e8e4de.pdf" -dEPSCrop -sFONTPATH="C:\Windows\Fonts" -f "C:\Users\23181\AppData\Local\Temp\tp714a7816_d749_44e8_a55f_a4b4a6d475ea.eps"

that the function you used (D:\Program Files\MATLAB\altmany-export_fig-d5538e9\export_fig.m) is from the expected location
and that you did not made a mistake in export_fig's expected input arguments
and that ghostscript is properly installed in D:\Program Files\MATLAB\gs9.50\bin\gswin64c.exe

Zachary

Santanu Bir

Changcheng Zhu

Peter Li

Very good code. thank you very much, amazing quality .eps figures

Konstantin Hermes

Ashneel Chandra

Lukas Jung

Leopoldo Losa

Sorry, mistake web page, cancel my comment

Michael Darmanis

Tunca Nuzket

Rajasi Desai

Georgios Etsias

Nicholas Turo-Shields

Femab

Xen

Very nice, thanks. But, how can I export a figure with a specific size in inches and resolution? Setting the size of the figure before exporting and then exporting at a specified resolution doesn't work, because the function crops out the white areas and you end up with the wrong size.

MS

Yoeri Boink

Maia Desamo

I love it

runze xu

Scott Karbashewski

Francesco Grassi

Kuntan Ni

Beautiful function! It saves me a lot of time on saving figures, and has been my default choice.

Lloyd Elliott

tong lee

nice

Giang Nam Nguyen

Samuel Cortinhas

ahmet ardahanli

George Pinto

Meng Wang

Work perfectly for other formats.
But to eps format, there is an error: pdftops not found although there is indeed pdftops.exe in the install folder on Windows platform. However, when matlab throw that error and open the dialog to locate pdftops, it does not show that file.
Tried the methods https://github.com/altmany/export_fig/issues/137 here. But no help because I could not find a libfreetype.6.dylib. Not sure it's because they are on Linux platform. But anyway, the error still exist on Windows.

khaoula karroum

Batool Abbas

Used it to successfully append pdfs!

Ray Wu

Gaszton

Works perfectly to save figures with transparent background to PNG.

Sim Mah

Thanks a lot

Jessica Vidmark

Am I the only one who is having a lot of difficulties installing the pdftops required folder? I don't see why it's so confusing.

Hebert Satria

Xiaolu Zeng

Good stuff! Helps a lot for papers! Thank u.

Haris Kunnath

Jerome Garnier-Brun

Patrick Gütz

Hi!
I found a problem with labels having subscripts. Creating a figure with 'CMU Sans Serif'-Font and exporting in e.g. eps invokes space before the first subscript letter. I need this font for consistency with the rest of the document. Is there a way to fix the issue? Short example:

x=[0,3];
y=[0,1];
plot(x,y)

xlabel('Text x_1+x_2');
ylabel('Text y_1+y_2');

ax=gca;
ax.FontName='CMU Sans Serif';
export_fig('Trial.eps','-transparent');

Nicolaj Hansen

Qiang ZHU

Thanks for this perfect tool!

Luca Freilino

Reece Nixon-Luke

Simply perfect

Jiacheng Deng

Ufuk Tamer

Sofia

Pau Packard

Sebastian Röthlin

What I was looking for. Also had the issue with the white diagonal line in the colorbar, but only in pdf (using the transparent option) but not in tif.

Michael Darmanis

Great tool!

Jullienne Franz

Sajid Raza

very useful toolbox

Hippo

I find export_fig to be very useful, and it does an excellent job in cropping the margin on the figure. I'm wondering if it is possible that the functionality of cropping is extracted as a more independent function, so that it can be very handy when we export the figure in formats not supported by export_fig, for example the emf format, which is a vector format, and is high compatible with MicroSoft Word. It will be much appreciated if the author or anyone else can do this.

Henry Giddens

Seung-Goo Kim

DAI WEIJUN

arnold

the PDF problem from the post before only occur if there is non-vectorized data in the figure, like an image with imagesc. However, all the elements then seem to get saved rasterized. All text, the labels, gridlines, everything.

arnold

-pdf does not produce a vectorized pdf file for me but it always had before migrating to a new win 10 r2018b setup. Any tips? Newest ghostscript is installed of course.

Dima

Jasvir Bahl

Tom Lindström

Pankaj

Thanks for sharing, it is useful. emf support would be deeply appreciated.

Shuoshi Zhang

Linwei Hu

Very very useful. Works perfectly in 2018a. Thank you very much for sharing it !

Damon Hyde

Waitsang Keung

Amazing function!

Christopher Elliott

This function solved the issue of non embedded fonts (Helvetica) in epstopdf figures for IEEE publications. Very helpful, thank you Yair Altman!

Fernando Zigunov

Doesn't export Latex fonts to pdf...

Yair Altman

SKG - export_fig does not [yet] support uifigures that were created using App Designer or the uifigure command, since it relies on Matlab's built-in print command, which is still not supported for such figures (at least as of R2018b).

Zhu Ruihen

SKG

Error using matlab.ui.Figure/horzcat
Conversion to matlab.ui.Figure from char is not possible.

Why am I getting this error?

Yasmin Samy

Thanks for this great code!!
Unfortunately, I having a minor problem. My figure also has a uitable.....how can i save both the graph and the uitable in the same figure? Currently, export_fig just ignores the uitable in the figure and saves only the graph.

w2=strcat(stn,'-Geo_ensemble');
export_fig(w2,'-m2');

krimou24

Jun Meng

It's an amazing function! However, I can't export -esp format. Since I'm using MacOS, there is no Ghostscript and pdftops for Mac. Does anybody know know can i solve this problem?

Farley Postgate

Found error. Needed to update 2018b path is all.

Sorry...

Farley Postgate

Not sure why but this worked great for me until 2018b (2018a was ok) . Now with 2018b I get the following error:

Undefined function or variable 'using_hg2'.

Error in export_fig>parse_args (line 1157)
options.aa_factor = 1 + 2 * (~(using_hg2(fig) &&
isAA) | (options.renderer == 3));

Error in export_fig (line 280)
[fig, options] = parse_args(nargout, fig, varargin{:});

Any thoughts out there?

Thanks,
Farley

Kouichi C. Nakamura

I should have known this function earlier. It's not straightforward to export high quality graphics from MATLAB figure. There are a lot to consider. But this function is a solution for many of those issues.

Efstathios Zavvos

This worked very nicely until I had to export a figure with left and right y axes. In that case, the figure output is always smaller horizontally i.e. if you set a 10x10cm square figure, the output figure will not be square but shorter on the horizontal axis.

Hyun Jae Jang

I found that the below issue was solved on R2018a

Hyun Jae Jang

Hi, I have used this awesome function well, but recently, I got a problem.
I export my figure in EPS format.
In MATLAB figure window, there was no problem.
However, in exported EPS file, the position of marker was slightly right and upper shifted.
I think it might be the version problem.... but I don't have any insight.
I use 2017a, ghostscript 9.21, pdftops 3.04 on windows 10 64bit.
The last chage log in export fig is % 09/04/17: Added -linecaps option (idea by Baron Finer, issue #192)
Thanks!

Chung-Chi Tsai

Xiaoyu Yu

hai

Xianglin

Thank you very much! That function is really useful!

Friedrich Schlueter

Thank you very much for this very useful and wonderful tool! The only thing, which could be hopefully solved is some kind of distortion of exported images with the "-native" option. It seems, that the algorithm for this option produces several tiles of the original image and the tiles are shifted against another for some pixel to much in the wrong direction. This could probably be some kind of rounding problem or something like that....

Léopold

I would like to point out the fact that export_fig does not look compatible with psfrag
https://ctan.org/pkg/psfrag

It seems that the eps file output by export_fig is modified with respect to print or saveas, such that psfrag does not replace that tag.

Can anyone else comment on that?

craq

I just struck a frustrating corner case. I was trying to export a new version of a figure, and got the error 'Could not create X.pdf - perhaps the folder does not exist, or you do not have write permissions'. It turned out that the previous version was open in acrobat reader, and Windows does not allow open files to be written to. Perhaps the error message could include a note 'if you are using Windows, please check that the file is not open in any other programs'?

Eric Eschner

Annu Singh

Yu Zou

Francisco

Eyal Tal

Can this be updated to work with axes created in App Designer?

Thanks

Josh Walker

Please ignore previous comment, just needed to run it in "function" form. Absolutely great. Thanks for your hard work!

Chris Hu

Sasha Nasonova

You are amazing and wonderful. Thank you!

Nico Spo

Jessie yu

Jens

Oleg Zinoviev

Taylor Allen

Really nice add-on and is simple to use. This is great if you are wanting to overlay computed surfaces or scatter plots of data from an image over the original image and still maintain the quality. Super helpful in making nice figures for publications!

Fredrik Gustavsson

When I use export_fig on an invisible figure ('visible','off') that contains uicontrols such as text boxes, push buttons, etc, mixed with graphs, the uicontrols do not get printed. If i do the same thing with the figure visible, everything gets printed. Is there a workaround/solution for this?

z8080

Very useful function, but it would be great if it also added support for EMF as it is after all the most MicrosoftOffice-friendly vector format!

Jonathan Müller

Hi
I didn't manage to use this function within the App Designer environment.
I get the error "Undefined function 'export_fig' for input arguments of type 'matlab.ui.control.UIAxes'."
Is this type of object not defined for this function?
Is it furthermore planned to make this function work within App Designer?
Would be really helpful since the regular options (like print etc. ..) are also nopt (yet) available in App Designer.

Yu Xiao

Caetano Melone

Mazin Mustafa

Solve too many problems for me.

Hong Nguyen

Nikhil Mukund Menon

Alexey

M Reza Tavakol

ho-yam

Li Jianmin

michele fari

Gianni Pedrizzetti

Great job, allow high quality images. I allows to save (at high resolution and any format) exactly what is shown in MatLab.

Lara Román

Mahak Singh Chauhan

Jonas Allgeier

FF

I try to save a scatter plot with transparent color dots (FaceAlpha = 0.5). However, when I save the figure to pdf, the transparent effect disappear. I check online, and it said it is an issue has been fixed in export_fig. But I don't know how to get back the transparent effect of my scatter plot. Is there a method?

Z C

A similar question as SG's came up. The pixels are not square and the figure is stretched. Any solution?

Li Carl

Enhanced Metafile (EMF) is expected.

JIN YU ZHANG

SG

When I export a figure which is larger than the screen resolution with the "-native" option, the pixels aren't square anymore. Any idea how to solve this.

Pooya89

Håkon Ånes

david samvin

Bob DA

Fan Yang

Lars Loetgering

lian xiang

Shane L

Frederick Zittrell

Borys Kowalewski

David P

gdgc

Ferit Akgul

Ferit Akgul

Thanks a lot for contribution. However, I cannot seem to export an image file with the original image's quality even though output image resolution matches.

imshow('file.png') --> displays at %33 zoom since image is 4000x1000 pixels
export_fig -native --> outputs image at the same resolution (4000x1000) BUT image is heavily pixelated. Original image quality is not preserved.

How can I keep original image quality?

David P

Harry Chellis

This is fantastic and makes life so much easier!
I have had trouble when exporting as a figure as a pdf the title always gets cut off though

Debejyo Chakraborty

Zhiyuan Mao

Léopold

Hello,

I have finally taken the time (actually a few minutes) to get the hand with it and I am fully satisfied of it.

It might seems trivial for most of you, but may I recommend that a short note (for instance in the description) describing how to use it be added?
I.e., that the user should unzip the zip file, place it wherever he wants in its local disk, then he should add in his code
and then his figure can be save calling
export_fig()
(and see export_fig file for details about available output and input arguments).
Hope that helps!

Homam BETAR

ren ren

It's really useful！ Thanks！

liangyu

It is very useful. Thank you very much.

abderrazak chahid

Thank you very much. It is very useful

To Minh Tan Le

Guoqing Wang

Jong Hwi Park

ashkan ha

Martin Storath

Easy to use. Excellent work!

Vojtech

Lilla Horvath

Stefano Sorti

NMG

Jeremy Priest

Rongxin Zhang

Thanks so much. And I downloaded the last version. I find that Matlab r2016a no longer has /SO, /DO, /DA, /DD in the file, the fix_lines function would not work. Could you please resolve that or release a r2016a compatible version?

fan Wang

Thanks so much,
such an amazing tool.
I have a question please, how we can export figure in format (.fig) using this tool?

thanks

Patrick Hammer

I use this code all of the time and love it. However, for my contourf maps with several axes or objects (like arrows), they take an inordinate amount of time to write to EPS. When I say a long time, I mean it might run for a day with no show of if it is even writing it, not even showing a filename in the folder it is being exported to. Do you have any suggestions on how I might speed this up? I use cropping to remove excess background space, CYMK for the journal I'm submitting to, and painters renderer. Any help would be appreciated, as this is beginning to drive me crazy. :(

AndyD

Joe

Josh Natanson

Great tool.

Matt J

I don't think the issue of 1 pixel extra padding was truly fixed. I see a faint rim around exported images when placed on a black PowerPoint background slide

Yair Altman

@MichaelBevis - The Xpdf project was moved to http://www.xpdfreader.com on August 10, 2017. I updated the description text accordingly.

Sherlock Hsu

babita verma

Hi, I was collating few matlab figures to one pdf using export_fig.Is it possible to add a matlab figure to a specific page of the existing pdf?
I know append can be used to add figure to existing pdf file but the problem is every time i mess up with the sequence (of figures ) I have to redo all the figures (in one pdf) again. So was wondering if a matlab figure can be added to a specific page of the existing pdf file.

Michael Bevis

This recommended link to xpdf software

> pdftops (install the Xpdf package): www.foolabs.com/xpdf

no longer seems to work, Is there another source for the xpdf package?

EP

How do I fix dotted lines blurring together for a 3-D plot? The 2-D plots look great, but in 3-D they blur together. I'm making a pdf so I believe the painters renderer is being used.

Nikki Brown

This worked a treat, thank you.

NING LIU

Daniel Wong

Mary Ann Harrison

zhidong cao

Julio Montecinos

Hiroki Watanabe

Jason McCune-Sanders

DrZoidberg

Kuifeng

Nicholas D.

Peter H Charlton

Mélodie

Awesome, thanx a lot!

wu jun

Ander Cruz

Daniel Niemann

Very nice and helpful function! However, it seems to have a problem mit date axes. I want to use your function to improve the quality of some time series plots with dates on the x-axis. When using your function, the created matlab figure has the first (oldest) date at the very right side of the axis and all subsequent dates shifted to the left. Then, it exports the described figure and after exporting it, the axis changes to the correct order with oldest to youngest.

It would be great if you could look into this issue.

Best,
Daniel

Marcus Victor

amelia grossman

Alexander Potrafke

Nathan Porter

This is the best solution I've found for creating high-quality PDFs. It's a lifesaver when I want to include graphics from MATLAB in a LaTeX document.

jon erickson

David George

Statovic

elvis ching

nice tool!
but it doesn't work after I use the tool 'freezecolors' , what can I do with it?

Ringo Cheung

Hi Yair,

Excellent app, easy to use. You save my day!

Thanks,
Ringo

Jeffrey Huang

Silvana Palacios

Genius! Thanks

Jianke Li

Excellent work. Thumb up!

MANG TENG

Anisa Oshafi

I had been searching for this one and I finally found it. Well done!

Arthur Degeneve

Thanks!

xinyu lei

Mehdi BRAHIMI

Dima

Nicolas Chartier

Seban

Bernardo

I often get an error saying that I don't have enough "thread space". I am appending 14 charts. What Could I do to solve that?

Dinant Kistemaker

good stuff!!!

Veronika

Please, I would like to transfer png images into tiff, but I don´t know, where I put (load) my images for this transfer. Because I have this error:

Error using get
There is no Binarizace_okoli_ 1.png property on the Root class.
Error in export_fig (line 265)
fig = get(0, 'Binarizace_okoli_ 1.png');

l l

nice job man!

Andrea Finke

Great! Works perfectly and saves me a lot of time.

Jay

that's OK!

Jeremy Poindexter

Mandeline Ferreira

Shervan Gharari

E_Z

Good function! However, it doesn't print axis values properly specially when there is something like x10(-15). My code is given below:
t = 0:1/4:1; % test range
xa = sin(2*pi*2*t);
plot(t,xa,'.-'); grid on;title('tom');
export_fig test.pdf -native -transparent

ty long

Alexandre Laurin

john doe

JINGYI WANG

Li Dong

Jiaqi Chen

SAI PRANITH

Nathalie

Hi,
I am plotting a grid of pixels in matlab and I have to overlay multiple grids on same figure using hold on (around 100). At the end figure become extremely heavy that if i zoom in a little portion of figure, it take computer to process an hour to zoom.
I was thinking to export figure on EPS format and then see the zoomed figure in EPS viewer. However, i am not able to see zoomed information of figure. Please let me know is it possible to preserve original figure information in EPS format so that when i zoom in EPS figure, I can see details just like in MATLAB?

David

Really useful function, thank you! However, there is a small bug that occurs when using the LineWidth option in conjunction with anti-aliasing:

figure(1), clf;
z = linspace(0,4*pi,250);
x = 2*cos(z) + rand(1,250);
y = 2*sin(z) + rand(1,250);
scatter3(x,y,z,'Marker', 'x', 'LineWidth', 4);
export_fig -a4

The saved figure will display points at default line width rather than the specified value.

Yusuf Said Eroglu

Hello everyone, I used this function to export my figures to PDF. Then I used those pdf figures in my latex paper. When I uploaded the paper, I got "fonts not embedded" error. Is not this function supposed to embed the fonts already? What else should I do to not to get this error?

Joris Meurs

Thomas Beauduin

*.EMF would be great

Neil Arthur

In order to export to the desired size, using:
set(gcf,'Position',figurePosition)
or
set(gcf,'PaperPosition',paperPosition)
does not work on its own. You also need to change the LooseInset property with
set(gca,'LooseInset',get(gca,'TightInset'))
Then use export_fig with no padding. Then the figure will print exactly to the desired size...Is this correct? Or am I missing something?

Leo Simon

Sorry, I downloaded the latest option and the issue I noted earlier has been fixed.

Leo Simon

It's a great addition, but there's one issue, which is that the padding option works only if options is a vector, which it isn't in my case. I hacked my code: on line 349 of export_fig, the third argument is hard-coded as a 1, if you change it to be options.bb_padding, then one can use the -p option generally. Hopefully this doesn't create other problems, but it seems to be working for me.

Aj_ti

got to rate this full star. easy to use and handy

Simon Wyss

Water_RC

Water_RC

Stefan Kopecz

Keith

I have enjoyed using this package for many years. Of recent I've started to use the Parallel Computing Toolbox (PCT). Are there any plans on getting export_fig to work with the PCT? PCT in parfor loops use the -nodesktop and -nofigure options which export_fig doesn't seem well set up to handle.

CS

Chuong Nguyen

one of the best toolbox. Thank you very much.

Igor Rutkowski

Very useful. The figure quality is very good

elvin feng

Good stuff here.

But I'm having an issue, when exporting to a tif and trying out the different options (-native, -q, etc) the output comes out the same resolution but the quality is diminished. 4x4 regions appear to be averaged into one which is quite the loss. Am I using the wrong options here to export or is this intended?

Alexandros Iliopoulos

des

This function has made my life a great deal better for the last 7 years. Thanks a lot to the developer/maintainer!

BUT: after the sudden death of my previous PC and subsequent complete system reinstallation, pdf figures exported with export_fig now come in Courier font. Makes for fancy retro hipster style graphics but is unfortunately not an option for any kind of publications, and no solution found locally so far - I had to go back to Matlab's built in print function ):

Has anyone experienced similar behaviour? Is the problem on Matlab's or Ghostscript's side, or somewhere else?

Some clues:
- The Font tab in the pdf's Document Properties states: "any (Embedded Subset)" - somewhere in the exporting process the figure's font (Helvetica, I believe) goes missing.

- current system specs: Windows 7, Matlab 2016b, Ghostscript 9.19

- Browsing through older pdf files, I found that any pre-reinstall combinations of various Matlab and Ghostscript versions up to R2015b / 9.15 worked. There, the pdf specifies "Helvetica" as its embedded font (and thus it also displays Helvetica/Arial).

des

Oliver Karger

Hi, this export package is great, the plot quality is so much better than with the built-in Matlab functions.

What I am wondering is in the pdf export, that the grid, which constists of faint grey lines in the Matlab figure becomes a dashed white line in the pdf export. Since I am using dashed lines to separate visually certain regions in the plot the now white dashed lines are overlapping with my annotation lines.

In the png export output the gridlines are still in a faint grey color.

Where can I change that to get the same result for the pdf export as well?

Thanks and best,
Oliver

susana

Hello Yair,

Excellent contribution.. But i'm struggling with '-append' option because I want to put two gui figures in the same file and with your function I'm able to do that, but I loose some of the handles of my figures (e.g. uitables, string boxes..). Any ideas what could this be?
Best regards,
Susana

xueping li

colorblindy

Alexander H

Thank you for filling the gap. This is extremely handy!

John

Zhou Wei

J S

Thank you very much for this. If I was choleric, you would have prevented me from beating up my computer because of the annoying and shitty handling of the print function. Unsuccessfully tried for over an hour to get rid of the outer padding of saved plots. With your script, it was about 8 minutes, including download time.

Kiran Sagar

I work on a computer where I don't have administrator rights. So, I can't install ghostscript. Is there any work around for that? (on Windows 7 - 64bit)

Aymerick ROUSSEY

Awesome thanks

kawofengche

Ian Bennett

Very good program. However, I experience an issue when trying to export images with semi-transparent plotted points (using MarkerHandle.EdgecolorData and MarkerHandle.FacecolorData). The image that is exported does not show my points as semi-translucent, as they are in the plot. Instead, they show up as opaque.

Ilkka Sillanpää

Gyan Raj Koirala

@Miles, you can try out the following code to specify file name.

export_fig (sprintf('figure%d',mm));

I used it in a loop eg. for mm=1:5

cunjie zhang

excelent

yangyang

Great function. Saved a lot of time.

Miles

I am having trouble specifying the filename when using this function...my code looks something like this:

...[code to make my figure]...

temp_str = strjoin({'filepath\',filename},'');
export_fig({temp_str})

When I do this, I still get a file saved in my directory which is named "export_fig_out.png". I was expecting that I would get a file with my "filename" that I specified.

Can anyone explain what I am doing wrong? I am slightly confused about the syntax for this function, I think.

Thanks!

Yue Chen

Great function. Thanks for sharing.

Pietro Binel

I have a question concerning crop! If I crop the image it won't be centered with respect to the plot box, because on the left side there is the YLabel. How should i modify the code so that the left space out of the box is equal to the space on the right (empty)?

many thanks!

Zhang

Maxim Khomiakov

laurie stephey

renders EPS figure beautifully that was a mess when using the matlab defaults. thank you!

Yiling Xiong

Daniel Cook

This is a life saver. I've used it to produce excellent figures for publications as well as presentations.

M FRZ

@ Yuri K: Thank you!

Emanuele Massaro

Hello unfortunately it does not work with geowshow and an image over a map.

s = size(Singapore);
matrix = rand(s(1),s(2));
geoshow(Singapore(:,:,1:3), R)
hold on
geoshow(matrix, R, 'DisplayType', 'texturemap','facealpha',.5);

And here the file of the image
https://www.dropbox.com/s/55o13cmyzf206uo/Singapore.tif?dl=0

if we do
export_fig test.png

it will not see the transparency as posted here:

Emanuele Massaro

Hello unfortunately it does not work with geowshow and an image over a map.

s = size(Singapore);
matrix = rand(s(1),s(2));
geoshow(Singapore(:,:,1:3), R)
hold on
geoshow(matrix, R, 'DisplayType', 'texturemap','facealpha',.5);

And here the file of the image
https://www.dropbox.com/s/55o13cmyzf206uo/Singapore.tif?dl=0

Yuri K

M FRZ: set(gcf,'color','w')

M FRZ

Hi , thanks for the code. how can I remove the gray border of the chart? export_fig gives me a graph with gray border (chart area color). I couldnt find the answer to this question.
Cheers

Nat anunta

Hanif

Wiviann

In order to make the code compatible with later MATLAB versions, you can change the code on line 14 in "using_hg2(fig)".

It should now be:
tf = ~verLessThan('matlab','8.4.0');

Earlier it was:
tf = ~graphicsversion(fig, 'handlegraphics');

Smilla

Raymond Phan

I've been using this script for years. Haven't gotten around to rating this script until now. Thanks for this script; awesome work!

zivan

Great Work.

Gabriel Mocan

awesome!

Andrea Carpi

Neil Bhattacharjee

Hi,

When I use this to convert a figure to a pdf/eps, I have "tiles" that are overlapping each other, causing for some filled circles to be cut in half, etc.

Is there any way to fix this?

Many thanks,

Qingjie

Hi,

When I use export_fig to create .eps figures, both the x label and y label are not centered with respect to the axes; instead they are centered with respect to the cropped figures. I am using MATLAB2016a on a 64bit Ubuntu system. The following code can be used to demonstrate the problem described above:

x=0:0.001:3*3.1415926;

y=sin(x);

plot(x,y,'r');

axis([0 3*3.1415926 -1 1]);

xlabel('xxxxxxxxxxxxYxxxxxxxxxxxx','FontSize',16);

ylabel('yyyyyyyyyyyyXyyyyyyyyyyyy','FontSize',16);

export_fig test.eps -painters -r500 -q100 -cmyk -transparent;

Neil Bhattacharjee

diane peurichard

Mingjian Cui

Felipe Uribe

Dimosthenis Floros

A great tool! Many thanks!

Louis

If we change the size of the figure showing in Matlab, the eps image size changes. Is there an option to resize to a specific eps file regardless of the figure?

amin rasoulof

A Lifesaver! I badly needed a transparent background in png output and it did it great for me.

Benjamin Bourguignat

Hello, I have a problem. I have 3 figures figure(1), figure(2) and figure(3). I try to put figure_hanfle=findall(0,'type','figure') and export_fig(figure_handle,'-pdf') and I have an error message "Handle must be that of a figure, axes or uipanel"...
Could you help me? I want to have a figure in each sheets of a pdf. Thank you

Diana Li

Thomas Bischoff

It works really good. :-)
Thanks

Lindsay Anderson

I am getting the following error in matlab:

I too have installed xpdf as directed but am having no luck. Any suggestions?

Thanks!

Todd Karin

I believe I've found a bug. Please try the following code. You see that the peaks of the sine waves in the plot do not correspond with the peaks in the image.

--

clear
clf

x = linspace(0,30*pi,1000);
y = sin(x);

h(1) = axes('position',[.1 .15 .8 .3])
plot(x,y)
xlim([0 max(x)])

h(2) = axes('position',[.1 .45 .8 .3])
imagesc(x,1,y)
xlim([0 max(x)])

export_fig('testFig2.pdf')

Damir Dominko

David Ho

Hi there, this tool is very capable. I have been looking for a similar tool to help me export a 3D plot with large amount of data that allows me to encode the axes/text differently from the data.

I came across epscombine and figure2eps but the tools are outdated. (see my question in the link below).

I wonder if you would consider adding those features to export_fig? Or does matlab natively already support them?

zlotnik

Awesome work, Yair! Thank you very much for creating, documenting and sharing this great function for us.

--
Ilya

zlotnik

Awesome work, Yair! Thank you very much for creating, documenting and sharing this great function for us.

--
Ilya

Luiz Carvalho

I had to change the line 131 in crop_borders from

to

Otherwise, it didn't work.

Juan Carlos

Quincy van den Berg

bubbleguy

I have been using your code for quite sometime and really like it. Thanks.

Recently, I noticed that in exporting the figure to, say, a PNG image, the minor ticks were not produced. Any suggestions.

Rongjie

Bogdan Dzyubak

Hi,

Thank you for the code!

Having one issue, though - the font of the labels on the colorbar becomes very tiny in the captured image. Any suggestions?

Linus

Christian Clauß

Hey, first thanks for this file!
I have a problem with exporting a figure to *.eps while using FontName 'Times' in Label and axis....

The exported *.eps image is always the same size and not depending on figure size.

My Matlab Version i use is R2015a.
Any suggestions?

Greetings and Thanks

Arabarra

Arne Zimmer

Hi,

thanks for this great file!

But one thing: I use R2015b. I copied crop_borders.m, export_fig.m, print2array.m and using_hg2.m to my matlab folder and then I use this command:
export_fig test2.tiff -native

The file test2.tiff is in both directions 2 pixels larger than the original!!

Is there missing something?? What is my error?

Pedro Mateus

Loved all this project. Just one thing, when I try to export to eps or pdf I receive a message "export: Command not found." but everything is done...

Best, Pedro

Ivan

Manuel Steinbrecher

Firstly: I love your script Yair, it's great and I use it alot! It really produces nice figures!

Secondly: I got a problem lately. I currently writing my dissertation thesis so I would like all my PDFs in CMYK colorspace, which worked fine for the first figure I made (I think at least).
But with another figure, I run into troubles as it seems not to save the PDF content in CMYK space. I am not sure how to check on it (only finding expensive tools for this) but when I open it in CMYK color space in Illustrator, colors change dramatically... I get the following warning when executing the script with these parameters (-pdf -cmyk -r300):

Warning: Multiple images & lines detected. In such cases, the lines might
appear with an invalid color due to an internal MATLAB bug (fixed in R2014b).
Possible workaround: add a '-depsc' or '-opengl' parameter to the export_fig command.
> In print2eps at 232
In print2array at 110
In print2eps at 394
In export_fig at 625
In MYFILENAME at 311

Yes, I am using R2012b because we have some old code that won't work properly in the newer versions of Matlab. Do you think that might be an issue? Or any other ideas? Possibilities?

Would appreciate help :)

Best,
Manuel

Marc Crapeau

Very precious tool, thanks a lot for that.

If it can help people: I had a problem using export_fig on figures created with functions of the mapping toolbox. The coast lines I was plotting together with my data were visible on the matlab figure but not on the file created by export_fig. To solve that I have used the uistack function to push my coast lines on top of the figure. For example:

% insert here complex mapping toolbox plotting operations
uistack(h_cl,'top');
export_fig('my_files.png')

Ivan

rahmouni

Harald Enzinger

I would like to thank the original author and the current maintainer for their outstanding work. For me, export_fig is a must!

People who write papers in electrical engineering or related fields might also take advantage of bibget. This is a tool I wrote to easily retrieve BibTeX entries from IEEE Xplore.

With export_fig and bibget, writing papers is much more fun! :-)

Chang

Youngmin Ha

Ahmet Karakucuk

Yair, can't thank you enough to show my appreciation for this function. I'd been using it for manuscript figures for over two years now.

Niekjuh

Francesco Ferrante

On El Capitan I cannot use export_fig to export into eps. Precisely, that's the error I get:

I also tried to install xpdf as indicated, but still the same problem. Could anyone please help me?

Francesco Ferrante

On El Capitan I cannot use export_fig to export into eps. Precisely, that's the error I get:

I also tried to install xpdf as indicated, but still the same problem. Could anyone please help me?

Delyle Polet

Simon Van Gorp

Great script! Do you know how I can export a panel within a tabular. The problem is that the panel original dimensions are not kept but the dimensions of the tabular are taken.

Not sure if this is a bug or intended ? Is a workaround possible ?

neo

This submission no longer (2014b onward) improves line styles in exported eps figures... As this file is still getting updates may be author should check this feature.

Tina Fuhrmann

I forgot to add the correct search path, sorry! With the current version I do not get the warning any more.

Sorry for posting twice the last time ... is there any way to delete a comment?

JoseLuis

Great tool! thanks for the contribution. I'm just having a bit problem. I'm loading and modifying an image of 360x360 pixels. When I export it with export_fig I get an image of 362x362. Could you give me a hint why? I'm using Matlab 2014b in Windows 8. Thanks!

Tina Fuhrmann

Recently I get the following warning message in R2015b when using export_fig with boxplot and plot:
Warning: graphicsversion will be removed in a future release.
In using_hg2 (line 15)
In export_fig>parse_args (line 797)
In export_fig (line 216)

Thanks for the great file, I am using it since a few months and I am thrilled :).

Tina Fuhrmann

Recently I get the following warning message in R2015 when using export_fig with boxplot and plot:
Warning: graphicsversion will be removed in a future release.
In using_hg2 (line 15)
In export_fig>parse_args (line 797)
In export_fig (line 216)

Thanks for the great file, I am using it since a few months and I am thrilled :).

Davide

It works pretty fine with R2015b.

Dan K

Note that saving to the clipboard was broken in R2015b. The fix is described in (apply at line 733):

Carlos Meza

Excellent contribution. I have problems with (surfc,meshc) not generated vectors. When I am using surf if generated. Any solution?. Thank you very much for your collaboration

vthuongt

Plotting works fine except of plots generated by using bar() or histogram().
There I can't get any transparent pdf files with vector graphics.
My command used was:
export_fig( 'histo.pdf','-pdf', '-transparent',figure(1))

vthuongt

Plotting works fine except of plots generated by using bar() or histogram().
There I can't get any transparent pdf files with vector graphics.
My command used was:
export_fig( 'histo.pdf','-pdf', '-transparent',figure(1))

xikang

Excellent when I want to get a transparent figure. Thank you very much!

Laura

Andy Hueni

PDF export works for me on Mac OS X El Capitan with R2015b after installing Ghostscript-9.16.pkg from http://pages.uoregon.edu/koch/.
Had to move to this package as the Matlab fillPage and print functions I used till now messed it up after the Capitan upgrade, can't say if it applies to Yosemite as well.

Laura

I've been using this function since forever to produce article-level figures with tight control of the dimensions

Yair Altman

@MSch - export_fig works well on R2015b. The removal of the builtin Matlab ghostscript does not affect export_fig, since export_fig does not depend on it. You can install ghostscript executable directly from http://www.ghostscript.com and then export_fig will use it.

I remind everyone that I will not respond to feature requests or bug reports in this comments section - if you have something to request or to report then use Github's issues page to report and track your issue: https://github.com/altmany/export_fig/issues

MSch

does not run with Matlab 2015b due to this: "MATLAB no longer ships with the Ghostscript® library. Remove all instances of code that use ghostscript.m." (see ReleaseNotes -> graphics -> Functionality being removed or changed)

I'll stick with 2015a till there's a workaroud, because I love this tool, especially the append_pdfs function :) Thanks!

David

I have been using export_fig for a long time. After switching to R2015b, it threw a warning about using an obsolete function (graphicsversion, I believe) so I got the latest version. This produces an invalid eps file,so the eps2pdf crashes. Preview also cannot open the eps file. The error report from ghostscript is
Error using eps2pdf (line 107)
Error: /undefined in bdef
Operand stack:
dom --nostringval--
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval--
--nostringval-- 2 %stopped_push --nostringval--
--nostringval-- --nostringval-- false 1 %stopped_push
1951 1 3 %oparray_pop 1950 1 3 %oparray_pop 1934
1 3 %oparray_pop 1820 1 3 %oparray_pop
--nostringval-- %errorexec_pop .runexec2 --nostringval--
--nostringval-- --nostringval-- 2 %stopped_push
--nostringval--
Dictionary stack:
--dict:1194/1684(ro)(G)-- --dict:0/20(G)-- --dict:78/200(L)--
Current allocation mode is local
Last OS error: Invalid argument
Current file position is 64
GPL Ghostscript 9.16: Unrecoverable error, exit code 1

Yu GUAN

Wonderful code

Cedric Noordam

Great tool, really improves the look of my graphs. Only thing so far is that cropping is either on or off, with no option to crop only top/bottom or left/right. I need this to have proper scaling of the plotbox area in Latex files. I had to fix it by just disabling left/right cropping in the crop_borders.m file disabling it for good. Would be great to have specific command for left/right/top/bottom cropping on or off. That's just a minor thing though.

Ben Webber

Great tool.

However, it seems that when text objects are positioned using normalized units, these positions are not properly retained when exporting the figure. I regularly use normalized units as I find these more intuitive. I'm using Matlab 2015b on MacOS 10.9 (the problem also occurs on Matlab 2012b).

Åsmund

I have been trying to solve the transparency issue for a long time. Now it's finally solved! Thank you!

NenaV

Hello Yair,
Has print2eps been tested with R2015b? It seems that the font mapping doesn't work.

I have a figure with Times font throughout (roman and bold). I made an eps using print2eps, but when I imported this in MS Word and tried to create a PDF file, I get a message like:
%%[ Error: invalidfont; OffendingCommand: findfont ]%%

Stack:
/Font
/Times-Roman-Bold

%%[ Flushing: rest of job (to end-of-file) will be ignored ]%%
%%[ Warning: PostScript error. No PDF file produced. ] %%

Thanks

Scott Williams

By the way the 1 star rating was an accident. I rate this file 6/5.

Scott Williams

I have also noticed greek letters distorted when using export_fig. I used to export as -png with compression -m3.
Exporting to pdf file removes the greek letters problem, and increases the quality of the plot.

William

I use this all the time to create plots, and it has been great! Recently I've noticed it does not create Greek letters correctly in the title. There is another post on Github noting the same problem for Matlab 2015a. I'm using Matlab 2014b on Windows 7. Does anyone know why this is happening or how to fix it?

Thanks for the help!

xinlu wang

Keegan Moore

cheng joylin

cheng joylin

David MERCIER

David MERCIER

Jitin Beri

Al

Hi

This is working great for me with exception of using it with the function Magnify on Figure. http://www.mathworks.com/matlabcentral/fileexchange/26007-on-figure-magnifier

For some reason, when Export_Fig runs, the x-axis of some of the magnified figures changes to become illegible. Its almost like some additional decimal places are added to the x-axis and they all overlap each other. As soon as Export_Fig is done, the axis goes back to normal.

Any help on this would be appreciated.

VItor ribeiro

This is my favorite tool to export graphics. However i found that i am not able to export markers that have a certain amount of alpha parameter(yes i found a way to do it and maybe you can find it if you dig on internet). When i export to eps the effect of shade in the background of the marker disappear. The way that i can set transparency in markers is the following:

sMarkers=h1.MarkerHandle; %h1 is line handle
sMarkers.FaceColorData = uint8(255*[0;0;0;0.5]); %fourth element allows setting alpha
sMarkers.EdgeColorData = uint8(255*[0;0;0;0]);

mashtine

Hi there,

This is a great code but I cannot seem to understand that when I try to use export_fig with larger font sizes, a grey box appears over my axis labels when I try to export the figure in a higher resolution. This is slowly driving me insane and I cannot seem to find anything on it. Perhaps it is my graphics card? Or just me? I use something like this for instance:

export_fig 'filename.png' -png -opengl -r150;

Hassan Naseri

It's an amazing tool.

Thanks for maintaining to support 2014 and 2015 MATLAB versions.

Vasilis Kapetanidis

Chenming Zhang

I am wondering why the font is extremely small under linux? I have tried both gentoo and ubuntu, the problem persists. matlab version also have been tested but all ends up with very small fonts.

Thanks

Deniz

Lavanya

Hi.. Actually i used this code last year to save fig as pdf and append the same, and it worked great..
but now when I try to use 'append', unwanted patches appear on the appended pdf file. I am using MATLAB 2014b. Will you be able to help me out.??
otherwise, the code works great.!! superb job!!

Stephane

Vital !!
Thank you very much !

Jens Keienburg

Solves all my issues with Matlab - LaTeX compatibility.

Ilya Belevich

awesome!

Alan Cole

FYI. For my comment on May 13th I corrected the issue by temporarily turning of Windows 7 UAC. When set to none it worked correctly.

John

John

R2015a, Mac Pro, Mavericks. Exporting to PNG. Works great, fixed my sizing and clipping problems.

Alan Cole

With the new version I receive the following error:

Warning: Path to ghostscript installation could not be saved. Enter it manually in C:\Program
Files\MATLAB\altmany-export_fig-b32040d\.ignore\ghostscript.txt.

The \.ignore\ghostscript.txt does not currently exist.

Peng Xu

Great tool

Gabriel Droulers

I have a problem with the exported .png file. The exponential notation on the top of the left Y axis does not show in the png exported image. Has anyone experienced this?
For instance I have a plot with value 0 to 5 "x10^-12". The exponential shows at the top of the axis but none of the formats I have tried (eps, pdf, jpg, png) show it.

Otherwise, nice work!

Ludwig

I have used this tool in matlab 2013a and it works perfectly. In matlab 2015a, the exact code gives a issue with exporting imagesc figures with colorbars. It always displays a white diagonal stripe from botton left to bottom left to top right. This occurs no matter which colormap is used. Has anyone tried it on 2015a so far?

ps : excellent work

It works excellent for me.

Kevin Moerman

Nicholas D.

Zulkifli Hidayat

Menno Poot

A great utility to export my figures to high quality .eps files.

biajia

When exporting Matlab2015a ".fig" file to ".pdf", the edges are cut off, especially the right side.

Sergei P.

simbaforrest

Jeff

Hi
I'm having trouble with matlab 2015a
Below is my error message

Error using eps2pdf (line 107)
Error: /undefined in bdef
Operand stack:
dom --nostringval--
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval--
--nostringval-- false 1 %stopped_push 1983 1 3 %oparray_pop 1982 1 3 %oparray_pop 1966 1 3 %oparray_pop 1852 1
3 %oparray_pop --nostringval-- %errorexec_pop .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push
--nostringval--
Dictionary stack:
--dict:1201/1684(ro)(G)-- --dict:0/20(G)-- --dict:77/200(L)--
Current allocation mode is local
Current file position is 64
GPL Ghostscript 9.15: Unrecoverable error, exit code 1

Error in export_fig (line 433)
eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);

Lei Ding

Hussein Sahli

atron

Converting a figure with non-standard screen size to pdf on Unix fails
-----------------------------------------

I am trying to convert figures with non-default screen sizes into pdfs:

% open matlab figure file
h=openfig_default(fig_file_name);

% change figure size to non-default size
set(h,'units','normalized','outerposition',[0.1 0.1 0.5 0.5]);

% convert fig file to pdf
export_fig('out.pdf','-pdf', h, '-nocrop','-transparent','-painters', '-append');

This works nicely on Windows, but on Unix the figures in the pdf all have the same default size. Any ideas?

Nicole Rüger

great, but i have a problem.
ich will append a few pdfs.
this pdfs have variable filesnames und paths. I got follow error:

Error: /undefinedfilename in (Auswertung_24-Mar-2015\\-2.2-\\2.2_Extraktionsgte.pdf)
Operand stack:

Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- false 1 %stopped_push
Dictionary stack:
--dict:1191/1684(ro)(G)-- --dict:1/20(G)-- --dict:77/200(L)--
Current allocation mode is local
Last OS error: No such file or directory
GPL Ghostscript 9.15: Unrecoverable error, exit code 1

thanks for help

comm@ZeoN

Serves the purpose very well. Thanks!

Sagar

I found the answer to my earlier question:
export_fig('exportfig_painters.png', '-png', '-painters', '-r300');

It works fine.

Sagar

Hi,
I had used this program successfully in the past for printing figures made in matlab. But now I am having a problem. I am trying to print a high resolution map made using geoshow in matlab mapping toolbox. But when I execute the command say export_fig finename.png -r600, the file is saved but only the axis labels are printed, and not the whole figure. I can still print several other figures successfully, so the problem must be related to the mapping toolbox. Could you please help?
Thank you very much.
-Sagar

Bob

Helped a lot, thanks!

Yair Altman

@Aniket - yes, export_fig does indeed accepts a handle to a figure/axes/uipanel

To all the others - you need to report the issue in the GitHub, otherwise they will not be tracked or fixed: https://github.com/altmany/export_fig/issues

Before submitting a new issue, please verify that it was not previously reported.

Jean

Hello,

I have the same issue as James Rankin in Matlab 2014b:

Error using eps2pdf (line 107)
Error: /rangecheck in definefont
Operand stack:
CMMI10 --dict:14/15(L)-- Font
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval--
--nostringval-- 2 %stopped_push --nostringval--
--nostringval-- --nostringval-- false 1 %stopped_push
1951 1 3 %oparray_pop 1950 1 3 %oparray_pop
--nostringval-- 1934 1 3 %oparray_pop 1820 1 3
%oparray_pop --nostringval-- %errorexec_pop .runexec2
--nostringval-- --nostringval-- --nostringval-- 2
%stopped_push --nostringval-- 1901 2 3 %oparray_pop
Dictionary stack:
--dict:1188/1684(ro)(G)-- --dict:0/20(G)-- --dict:121/200(L)--
Current allocation mode is local
Last OS error: Invalid argument
Current file position is 90501
GPL Ghostscript 9.15: Unrecoverable error, exit code 1

Error in export_fig (line 442)
eps2pdf(tmp_nam, pdf_nam, 1, options.append,
options.colourspace==2, options.quality);

Error in fit_ramsey (line 210)
export_fig(['fit_' filename], '-pdf');

Unfortunately, his fix is not working for me... It was working well with 2012b, I don't understand, as I am working with standard fonts...
Anyway, great soft, very usefull for scientific works !

Aniket Vagha

Brilliant tool! Image quality in pdfs is really good.

I was wondering if in case of multiple figures, could we use figure handles when using export_fig?

Sauro Salomoni

Elizabeth Jones

Great code! It worked without any fiddling in R2014b and created high-quality PDFs that I can use for professional presentations, posters, and publications. Thanks a lot for making and maintaining this code.

Durga Lal Shrestha

I have the legend at the Southoutside with horizontal orientation. When the box of the legend is set to 'off', a little bit bottom part of the legend is also cropped when exporting figure to eps and pdf (no problem with png). There is a no problem with box outline. The problem persists in MATLAB R2014b.

Does anyone else have similar issue?

Thanks.

Kai Shi

I added a rectangle box in the figure and change the transparency of the box to 0.3. However, when I export the figure into latex. The transparency of the box is still 100%. With and without the -transparent option shows the same results. The code of generating the box is shown below:

annotation(hCCs,'rectangle',rectSize,...
'FaceColor','r','FaceAlpha',0.3,...
'LineStyle','none');

Javier Paredes

Thank you for this library, it is really usefull! Unfortunately, I am having serious issues with export_fig, specifically with the fileparts(tempname) portion of the code that specifies a temporary folder that the program uses to create/delete temp images. It is trying to use the system32 folder for one of our users and it is giving him access violation errors and crashing. I would like to be able to specify my own user specified temporary path on his computer that he does have read/write access to. This is not a capability of the tool out of the box but could be a simple optional addition that would save us a lot of grief. For now, I will have to do this myself on my export_fig copy. Thanks!

Tero

Tero

Erik

James Rankin

I was receiving the following error after upgrading to Matlab 2014b (in Ubuntu 14.04):
------------------------------------------
Error using eps2pdf (line 107)
Error: /rangecheck in /findfont

...

Error in export_fig (line 442)
eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);
-----------------------------------------

I fixed this by commenting the following lines in eps2pdf

fp = font_path();
if ~isempty(fp)
options = [options ' -sFONTPATH="' fp '"'];
end

Yiqun Yang

To be more specific, here is the example code.

figure(1)
plot(1:100,1:100)
xlabel('Frequency (Hz)')
ylabel('attenuation (Neper/m)')
set(gca,'fontsize',16)
export_fig test -pdf -transparent

Yiqun Yang

Hi,

First thanks a lot for providing such a wonderful toolbox!

However, here I've found a bug when I switch to Matlab 2014b. In Matlab R2014b, when I was using the toolbox to generate pdf figure as:

export_fig ConvEstimateatten -pdf -transparent

The margin of the figure is not cropped as desiered. Could you have a look at it?

Thanks!

Tintin Milou

Hi,

I've got another issue: How can I save the file in a different subfolder. I created a subfolder Fig and then, tried:

export_fig ../Fig/fig.pdf;

but that gave

Error using eps2pdf (line 107)
GPL Ghostscript 9.10: **** Could not open the file ../Fig/fig.pdf .
**** Unable to open the initial device, quitting.

Error in export_fig (line 442)
eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);

What am I doing wrong?

Tintin Milou

Hi,

I'm still a bit puzzled how to display tex symbols. For instance, one of my titles is
title('\pi^w')
and is properly displayed in the figure, but not the printed pdf (there, I get a colon to the power of w). I'm using the latest version of texshop 3.49.
Thanks!

Martin

To clarify, I'm trying to export a plot with a legend from a GUI axis using export_fig(handles.myaxis, filename). The legend does not show. If I plot with a legend from the command window and save the figure with export_fig the legend shows correctly.

Martin

Excellent function!

However, using 2014b, the legends disappear from my plots. This does not happen with 2014a. Is there a workaround or missing argument for 2014b?

Yair Altman

@Ian Zammit - the utility's changelog is listed at the bottom of this webpage.

@Linh, Ruben, Iain - please create corresponding issues in Github (check if the issue already exists there, before posting a new one). I have just received ownership of export_fig's maintenance and it could take me some time to dive into things and be able to fix them, so please be patient.

Bart Boesman

Linh Nguyen

Excellent tool! Thank you a lot. It works for most cases for me, except when I need to plot and export a big field (200x300, pcolor). Could anyone try and tell me why I cant get a resolved image please? Results I got is also in the folder:
https://www.dropbox.com/sh/41yxaivtfkf8uzn/AABm-AMXI-0zTGedz8IgMPb9a?dl=0

Ruben Luis

Brilliant contribution!
However, it seems that something significant has changed when using R2014b. It does not seem to be possible to reduce the thickness of axis borders. Can you advise a workaround?

Ben Puttnam

Ehsan

Very very helpful, and easy to use.

Ragheb

Hi

export_fig works perfectly for small figures when I use this command: "export_fig test.pdf". However, using the same command, Matlab crashes for large figures and it gives me this error:
Exception type: Bus Error (0xa) at pc=7fff887be082

Also, I tried export_fig test.eps, but it does not even work?

Many thanks
Ragheb

Ragheb

Hi

export_fig works perfectly for small figures when I use this command: "export_fig test.pdf". However, using the same command, Matlab crashes for large figures and it gives me this error:
Exception type: Bus Error (0xa) at pc=7fff887be082

Also, I tried export_fig test.eps, but it does not even work?

Many thanks
Ragheb

photoinduced

from my experience works perfectly! Is there a list of changes for the version uploaded 08/12/14? The one within export_fig and some other .m files seems not to be updated

Iain

Hi Oliver,

Thanks for an excellent function!

I am using a current version of export_fig (today), OS X 10.10.1, ghostscript 9.15, and Matlab 2014b. All works fine when I set up a figure and run:

export_fig(fname,'-pdf',fh);

However, if I then run:

>> set(groot,'Units','normalized')

I now get:

>> export_fig(fname,'-pdf',fh);
Error using eps2pdf (line 107)
Error: /configurationerror in --setpagedevice--
Operand stack:
--nostringval-- (%%BoundingBox: 0 0 0 0) --dict:1/2(ro)(G)-- --nostringval--
--nostringval-- (%%BoundingBox: 0 0 0 0) 1 0 0 false --dict:1/1(L)--
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2
%stopped_push --nostringval-- --nostringval-- --nostringval-- false 1 %stopped_push
1951 1 3 %oparray_pop 1950 1 3 %oparray_pop --nostringval-- 1934 1 3
%oparray_pop 1820 1 3 %oparray_pop --nostringval-- %errorexec_pop .runexec2
--nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval--
%ztokenexec_continue (scanner state) --nostringval-- --nostringval-- --nostringval--
--nostringval-- --nostringval-- --nostringval-- 1913 10 3 %oparray_pop
--nostringval-- --nostringval-- --dict:1/10(L)-- --nostringval-- 16 %dict_continue
Dictionary stack:
--dict:1189/1684(ro)(G)-- --dict:0/20(G)-- --dict:81/200(L)--
Current allocation mode is local
Last OS error: Invalid argument
Current file position is 266
GPL Ghostscript 9.15: Unrecoverable error, exit code 1

Error in export_fig (line 442)
eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);

The output is now a blank PDF. Clearly, I can work around this by not invoking:

>> set(groot,'Units','normalized')

That said, it would be nice to have export_fig resilient to this setting.

cheers
Iain

Jiri

Great tool!

Steven

Hi Oliver. Sorry. I have not heard about GitHub before. Otherwise I would not bother you asking here.

I created an issue.

Thank you.
Steven

David Nolan

Great function and badly needed for HQ figures for publishing. You have my thanks Oliver.

Valjean

Sorry, never heard of GitHub. Now I see it at over there above the Download Zip button. Not familiar with it.

Oliver Woodford

Philipp: There is absolutely no chance without an issue raised on GitHub.

usr0815

Is there any chance that there will be a fix for the totally "jagged" lines all along a graph when exporting to either of those formats: png, eps, pdf, ... ??

The strange thing is: if I use saveas PNG, the Problem is not occuring. With export_fig (PNG) is occurs. So I suppose export_fig first creates a vector format and afterwards a PNG of it, which can explain that.

Anyway: I need MATLAB 2014b for some other features and ask myself if there is any chance to get this bug fixed?

Oliver Woodford

Valjean, R2D2: For the 100th time (and beginning to wonder what is wrong with people), I do not address issues placed in the comments. If you want me to look at your problem, raise a GitHub issue and we can talk.

Valjean

Update: export_fig works fine on the screen-sized figures when I remove the
'-transparent' argument.

Valjean

I want to clarify my previous comment. The script worked for the normal-sized figures, but the one that it choked on was the size of the screen if that makes any difference or helps diagnose the problem.
I create the figure, then resize the figure using the following lines of code:
h=figure;
set(h, 'Position', get(0,'ScreenSize'));

The figures that did save successfully were those that had not been resized.
Any thoughts?

Valjean

Thank you for this script, Oliver. I've been using it successfully for the past few years. However, I recently upgraded from MATLAB 2009 to 2012b, and I'm having nothing but problems. First, I had the same error that Derek got (posted 07 Jun 2013). So, I downloaded the latest version just now and re-ran. Now, I am getting the following error:

Array dimensions must match for binary array op.

Error in export_fig (line 283)
alpha = round(sum(B - A, 3)) / (255 * 3) + 1;

Error in SavePlotsFnc (line 3)

export_fig(strcat(dirname,'\',sn,fname,'.png'),'-png','-transparent',figh);

R2D2

I placed the wrong error message in the previous post. The message I get with GS 9.10 is:
Error using eps2pdf (line 107)
Error: /undefined in bdef
Operand stack:
dom --nostringval--
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval--
2 %stopped_push --nostringval-- --nostringval-- --nostringval-- false
1 %stopped_push 1900 1 3 %oparray_pop 1899 1 3 %oparray_pop
1883 1 3 %oparray_pop 1771 1 3 %oparray_pop --nostringval--
%errorexec_pop .runexec2 --nostringval-- --nostringval-- --nostringval--
2 %stopped_push --nostringval--
Dictionary stack:
--dict:1177/1684(ro)(G)-- --dict:0/20(G)-- --dict:77/200(L)--
Current allocation mode is local
Last OS error: Invalid argument
Current file position is 64
GPL Ghostscript 9.10: Unrecoverable error, exit code 1

R2D2

@Oliver. Tried ghostscript 9.10 and 9.15. Neither worked. Currently getting an error message:
Error: File: ghostscript.m Line: 35 Column: 1
Function definitions are not permitted in this
context.

Oliver Woodford

Steven: Sorry I have to repeat myself again. I don't know, and I won't look into it until you raise a GitHub issue. Thanks.

Steven

Thanks for the great function. Sorry I have to mention my question again.

Why does the function can not save figures, in log-log plot correctly, when the range is too small? (It prints the true value instead of 10^...)

Steven

Oliver Woodford

R2D2: Unfortunately I can't fix bugs in either Yosemite or Ghostscript. However, if you install Ghostscript 9.10 from here:
http://pages.uoregon.edu/koch/Ghostscript-9.10.pkg
does that fix things for you?

R2D2

Please fix the bugs that prevent this package from working with Mac OS X Yosemite + Matlab R2014b!

Thanks.

Bob

update for mac users: I may have found the issue. If you have texshop installed make sure you are at version 3.44. I updated ghostscript separately and had problems, I updated texshop and voila, export_fig appears to work as before. Speculation: the texshop installer does something the separate ghostscript package didn’t.

Bob

Has anyone gotten pdf export to work on yosemite/2014b? I’m using Ghostscript 9.15. I would appreciate anything your working setup. Thanks.

Yuewu

h1u1k1

As noted earlier, this really nice function does not work with matlab2014b on MacOS (Yosemite) 10.10.

h1u1k1

Indra

how can I use this one to save multiple files?

BERDIN

Carl Wouters

Really nice !
Only one thing missing: SVG
Would love a real SVG creator.

Martin

Thank you for this great function! Just one question: even when I use the -native option the final resolution of the image is different than the size of the matrix that has gone into the image. E.g., I have a 2048x2048 image, but after using export_fig (with the -native option) it returns a 2052x2052 image [currently using '-m4 -bmp -native' as options]. If I don't use that option it returns a 3176x3176 image.

Do you have a suggestion as how to get the exported image to match the size of the matrix?

Oliver Woodford

Michael, Adam: Surely one of you can (a) read and (b) file an issue on the github page, to which I will respond. I can't help you with what you've provided. Thanks.

Michael

With a code perfectly working on OS 10.9.5 and Matlab 2014a, I got the exact same issue than Adam, but on a OS X 10.10 (final release!) with Matlab 2014b and Ghostscript 9.15...

Error using eps2pdf (line 107)
Error: /undefined in definefont
Operand stack:
CMSY10 --dict:14/15(L)-- Font
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- false 1
%stopped_push 1951 1 3 %oparray_pop 1950 1 3 %oparray_pop --nostringval-- 1934 1 3 %oparray_pop 1820 1 3 %oparray_pop --nostringval--
%errorexec_pop .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- 1901 2 3 %oparray_pop
Dictionary stack:
--dict:1188/1684(ro)(G)-- --dict:0/20(G)-- --dict:121/200(L)--
Current allocation mode is local
Last OS error: Invalid argument
Current file position is 71195
GPL Ghostscript 9.15: Unrecoverable error, exit code 1

Error in export_fig (line 435)
eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);

Steven

The function is magnificent.
Except that sometimes for me a problem arises when exporting!

In loglog plot, the label ticks are not written correctly, I mean they should be something like 10^(2), but they are 100.

Strange is that this only happens for y-axis and x-axis is fine!

I looked it up a lot in the internet, but could not find the solution. I have not been able to resolve it by changing tickmode to manual or etc.

Any other solution?

Thanks!

Steven

George

Peter Pablo

Eric

Thanks a lot for the great work

Christian

I encountered a similar issue as described by Emma. However, it works fine for linewidths>0.75 pt, but for smaller linewidths the lines seem to be set to 0.75 pt when exporting, i.e. when exporting lines of 0.5 pt width (or any value<0.75), it will export them as 0.75 pt, when exporting lines with 1 pt width (or any value >0.75 pt) it exports them with the correct width.
The problem does not occur in R2014a.

Tremendously useful function. However, I seem to have issues getting it work in 2014b on Mac OS X Mavericks (10.9.5). Since upgrading I get the following error whenever I export to eps:

Error using eps2pdf (line 107)
Error: /typecheck in /findfont
Operand stack:
CMMI10
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval--
--nostringval-- 2 %stopped_push --nostringval-- --nostringval--
--nostringval-- false 1 %stopped_push 1916 1 3 %oparray_pop
1915 1 3 %oparray_pop --nostringval-- 1899 1 3
%oparray_pop 1787 1 3 %oparray_pop --nostringval--
%errorexec_pop .runexec2 --nostringval-- --nostringval--
--nostringval-- 2 %stopped_push --nostringval-- 1868 1 3
%oparray_pop
Dictionary stack:
--dict:1184/1684(ro)(G)-- --dict:0/20(G)-- --dict:121/200(L)--
Current allocation mode is local
Last OS error: Invalid argument
Current file position is 90356
GPL Ghostscript 9.10: Unrecoverable error, exit code 1

Error in export_fig (line 435)
eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2,
options.quality);

It seems to be an issue with ghostscript, but any hints as to how to fix it would be gratefully received!

Thanks!

Emma

I absolutely love this tool, but I have a problem using 2014b. The lines on my exported figures are really wide now. The exact same code run in 2014a is perfect, but the new linewidths are unusable.

Fabian Schrumpf

Oliver: I accidentally did not use the most recent release of your script. After updating, it works as great as before in 2014b as well. Thank you.

Yisheng Xu

It's a great tool. The only flaw that I found is the LineWidth and FontSize of exported vector image (pdf) is slighlty bigger than the sizes specified in MATLAB (e.g., LineWidth becomes 0.735pt and unadjustable; FontSize of 10pt becomes 10.29pt) Any way to fix it? Thanks!

Oliver Woodford

Fabian: R2014b works for me. If you have a reproducible error I suggest you provide me the code in an issue on github.

Fabian Schrumpf

I love this function and use it almost daily to export Matlab figures to pdf and postprocess them in other programs.

However, in Matlab 2014b Mathworks introduced the new graph design and the export to pdf/eps is not possible anymore, giving the error:

Error using eps2pdf (line 100)
Error: /undefined in bdef
Operand stack:
dom --nostringval--

I would highly appreciate if this could be fixed to run with the most recent Matlab version.

Fabian Schrumpf

Malte

Great job, thanks! However I am faced with the following problem... I used "patch" for plotting and the "FaceAlpha" property. After the export the background is black (*.png, transparent, opengl). Any ideas???

ustc

it's very good!

Micke Malmström

Robert Richardson

Robert Richardson

M S

Love this function. Transparency in .pdf/.eps would be *hugely* appreciated, I still use plot2svg when trying to save images with patch transparency.

Fei yang

Pretty good!

Ander Biguri

This fileexchange should DEFINITELY be added to matlab as a feature. Amazing.

Tobias Benjamin Gram

Liang Haixiao

Juan Deaton

mf0000

This looks as a function I might as well quickly fall in love with. However, I am in troubles with how to make it work. I do not find it so straightforward how to install Xpdf on mac, OS X. Can anyone help me with step-by-step instructions on proper installation commands in the terminal?

Karen

Selecting the location for the system version of ghostscript did not work for me. I am using matlab 2014a on a mac (10.9.4). My ghoscript installation is via MacPorts, and installs in /opt/local/bin/gs. My default shell is csh, not bash.

I was able to get the ghostscript.m script to work by changing the mac-specific 'export DYLIB...' commands (bash syntax) to 'setenv DYLIB....' (csh syntax).

I did not find an easy way to check what shell the user is using, but perhaps some checking for this could be added. Since the fix requiring the environment variable to be set has been around for about a year in your code, I suspect not many users have csh as their default shell, either under unix or OSX systems.

I have been using export_fig for several years, and am glad to have it back with my new laptop.

Oliver Woodford

Arnold: Try using imsc from my sc package. It doesn't use patch objects, but can still fill in NaNs with any colour you want.

arnold

I use imagescnan quite a bit. However, I can't export those figures as pdf since the white patches masking the nan areas are always dropped when using export_fig. I can't seemt to find a way to keep the patches. Exporting using standard pdf export works fine in this regard, yet it's very clumsy.... that's why export_fig is always first :)

plot with transparency in the patches not rendering in pdf correctly (the patches are given a solid color). How can this be fixed?

Haowen

arnold

Hi Oliver, still having problems exporting patches and lines or symbol.
I can use uistack or uistack2 from the file exchange here and get good looking results BUT, if I export PDF using export_fig the patch is always in front of everything else. Maybe you can look into that and fix it! thanks Arnold.

Mei June

Is there a way to use this great tool in the editor's publish function?

So that pressing the publish button yields a report with images and graphs as specified with parameters in this export_fig tool?

jianfeng zeng

I don't know how to set the DPI and size of figure
outputted by export_fig. Could any friend tell me about it? thanks very much!!!

Noah Levine-Small

Export_fig has been a life saver. Unfortunately, I now get the following error:
Error using eps2pdf (line 107)
Error: /undefined in bdef
Operand stack:
dom --nostringval--
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval--
--nostringval-- 2 %stopped_push --nostringval-- --nostringval--
--nostringval-- false 1 %stopped_push 1932 1 3
%oparray_pop 1931 1 3 %oparray_pop 1915 1 3
%oparray_pop 1803 1 3 %oparray_pop --nostringval--
%errorexec_pop .runexec2 --nostringval-- --nostringval--
--nostringval-- 2 %stopped_push --nostringval--
Dictionary stack:
--dict:1189/1684(ro)(G)-- --dict:0/20(G)-- --dict:77/200(L)--
Current allocation mode is local
Current file position is 64
GPL Ghostscript 9.09: Unrecoverable error, exit code 1
Error in export_fig (line 424)
eps2pdf(tmp_nam, pdf_nam, 1, options.append,
options.colourspace==2, options.quality);

any ideas?

Junghwan

Many thanks to Oliver for the great code.
One issue that I encountered:
When exported in eps format, all my tweaks on the plot legend are reset to default.

Baptiste

Tristan

Thanks for the great code, and the ghostscript error fix! it suddenly didn't print eps or pdf anymore, but now works beautifully again
..Afif: export_fig(gcf,'filename','-eps')

Sven

Hello,

Thanks a lot for that beatiful code. Works quite good.
However, there is a bug: one cannot use the symbol "%" within the file name:

When I type: export_fig(f3, 'Post-Process Estimates - diff. weight (+5 +10 +15)kg, Amp 10','-pdf','-q0','-a1','-r160','-nocrop') % lowest quality, no anti-aliasing, reduced resolution

it creates a nice pdf.

However when I add the symbol "%" at the end of the name, that is: Amp 10% I get a strange error message:

>> export_fig(f3, 'Post-Process Estimates - diff. weight (+5 +10 +15)kg, Amp 10%','-pdf','-q0','-a1','-r160','-nocrop')
Error using eps2pdf (line 107)
**** Unable to open the initial device, quitting.

Error in export_fig (line 435)
eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);

A bug?

Afif

Can someone please provide an minimalist example of how to export and .eps image using 'export_fi'? I am having a really hard time using it. Thanks in advance.

Tobias Benjamin Gram

After updating to R2014b, the crop function for PDF seems not to work properly. This is my test code:
--------------------------------------
x = -100:0.01:100;y = -3.*x.^2-3.*x+4;
figure,plot(x,y,'--')
xlabel('x-axis'),ylabel('y-axis'),title('title'),legend('function')
export_fig('fig1_q101_painters','-pdf','-q101','-painters');
export_fig('fig2_painters','-pdf','-painters');
export_fig('fig3_pdf','-pdf');
export_fig('fig4_nocrop','-pdf','-nocrop');
export_fig('fig5_png','-png');
export_fig('fig6_bmp','-bmp');
export_fig('fig7_jpg','-jpg');
----------------------------------------------
The png, bmp and jpg is being crop perfect.

Bennet Luck

Most used function at the moment, great!

Preetham Manjunatha

Extremely useful function!

murat

Hugo Mendonça

Morteza Shahpari

Morteza Shahpari

Dirk kok

If you are writing documents which require matlab figures this is a must have program.

Richard

First of all, this program is totally awesome. But... I'm having a problem with R2014b running on Windows 7. After creating a very simple plot, I get this error information.

Error: /undefined in bdef
Operand stack:
dom --nostringval--
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- false 1 %stopped_push 1862 1 3 %oparray_pop 1861 1 3 %oparray_pop 1845 1 3 %oparray_pop 1739 1 3 %oparray_pop --nostringval-- %errorexec_pop .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval--
Dictionary stack:
--dict:1153/1684(ro)(G)-- --dict:0/20(G)-- --dict:69/200(L)--
Current allocation mode is local
Current file position is 64
GPL Ghostscript 8.64: Unrecoverable error, exit code 1

I'm also confused as to why it's using Ghostscript 8.64, as I've installed 9.14 and changed 'path_ = user_string('ghostscript');' in ghostscript.m to 'path_ = user_string('C:\Program Files\gs\gs9.14\bin\gswin64c.exe');'.

talha

Debejyo Chakraborty

Actually exports vector pdf, cropped accurately! Thanks for this. Saves me a ton of time.

daniel

Wow, what a great tool! Saved me a lot of trouble, Thanks!!!!

Hassan Naseri

Great new version. Finally the problem with interactive plots, e.g., "impoint" or "impoly", has been resolved. :)

Christoph Gugg

great, now works with the prerelease of R2014b on OSX 10.9.3

Jorge

Alexander

Yifan

Yifan

George

Exactly what I needed. It actually gave me an eureka experience in my work. Thank you so much.

IRIN SAJAN

awesome...!!!!:)

Seyed F Yousefian

Awesome! This is exactly what I have been looking for.

mitilma

great! this saves my day, thank you!

Wang

Rashmil Dahanayake

Figured it out.
file_name=sprintf('plot_%d',x);
export_fig(fullfile(file_name),gcf, '-m2.5');

Rashmil Dahanayake

I'm try to use this script to automatically plot all columns saved in an array. Say if I have a 3x2000 matrix, I want to plot 3 raw vectors and save plot_1.png, plot_2.png and plot_3 png. Can I pass a string variable export_fig.

code:
% auto plotter
t=0:.001:2;
y1=2*sin(2*pi*t);
y3=2/3*sin(2*pi*3*t);
y5=2/5*sin(2*pi*5*t);
Y=[y1;y3;y5];
% real code begins here
n=size(Y,1);
for x=1:n;
taggy=sprintf('C=%d mF',x); % title
file_name= sprintf('plot_%d.png',x); % file name to be plot_x.png
plot(t, Y(1,:));title(taggy);
export_fig file_name -m2.5;close(gcf);
end

yun

jACK bROUDY

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

Ahmed

Wesley Allen

cfwen

awesome!

Cecilia

fei YANG

FF Lee

I must say that this is the best MATLAB code I ever use. It works even on my old version (7.0.4 R14) MATLAB. Many thanks to the author. :)

FF Lee

FF Lee

Erik

Finally a comprehensive figure exporting tool for MATLAB. I gratefully use it to create hi-res vectors from my figures, which is something that is not easily done in a useful fashion.

Erik

Finally a comprehensive figure exporting tool for MATLAB. I gratefully use it to create hi-res vectors from my figures, which is something that is not easily done in a useful fashion.

Oliver Woodford

I repeat, please email me bug reports rather than posting them here. Better still, fork the repository, fix the bug, and create a pull request.

Hassan: Your example worked as expected on my system.

Alvaro: Feel free to email me a minimal working example.

Hassan Naseri

1. Thank you for the great tool which I use it for all my graphic exports.

2. A problem: If a plot contains an "impoint" or "impoly", or probably any of these interactive objects from image processing toolbox, the output of export_fig simply doesn't show them. The problem happens only when exporting an axes not the whole figure. I would very much appreciate any suggestion?

figure()
handle = subplot(1,2,1);
impoly(handle, [1 1; 2 2; 1 2])
export_fig('test.pdf', '-pdf', '-transparent', handle)

Alvaro

Great tool, thanks for it !
I'm having the following error passing uipanel to export_fig
The name 'OuterPosition' is not an accessible property for an instance of class 'uipanel'. (im using matlab 8.1)

Matt

Aidan

Quan

Samuel Macedo

Oliver Woodford

Jo: Many thanks for the bug report. However, I do ask (in the description above) that people email me bug reports, rather than post them here.

Jo

First of all: great tool! I'm using it a lot.
Second: Matlab FileExchange Commenting is driving me nutts :-) (should've peeked into the previous comment)
Third: (main reason for my post) I encountered a tiny bug in the script, appearing as follows:
1. Create a figure
2. Create multiple axes inside
3. Draw imagesc in each axis
4. Disable axis labelling (axis off)
5. Draw e.g. a coloured rectangle in each image
=> The export will show the rectangle black in all but the first axis

Minimal example:

figure;
set(gcf,'Position',[0 0 1000 500]);
axes('position',[0.0 0.0 0.5 1]);
imagesc(rand(24,24));
axis off
rectangle('position',[8 8 8 8],'EdgeColor','r','LineWidth',2);
axes('position',[0.5 0.0 0.5 1]);
imagesc(rand(24,24));
axis off
rectangle('position',[8 8 8 8],'EdgeColor','r','LineWidth',2);
colormap gray
export_fig('tmp.pdf','-pdf');

Best wishes and thanks in advance for any hints or clues!

Jo

Arg, this commenting interface in FileExchange is driving me nutts... forgot to remove a .*m in both imagesc... sry for that :)

Jo

Jo

Martin

Pooya89

Aaron True

Sorry for the multiple posts, apparently I can't rate it then comment without it automatically submitting my rating.
Anyways, love it so far, thank you!

I'm trying to resolve 2 odd issues. First, the negative signs on my axes tick labels show up as empty boxes when I open the pdf in Adobe Reader, which makes me think there is a missing font package etc. in my Adobe install; however, when I open the pdf in Ghostscript there is no symbol at all (minus sign or empty box), just the number on each axis tick. I'm using Adobe Reader XI which came installed on a new Dell PC (< 6 mos. old), and I just downloaded Ghostscript 9.10 today.

Second issue is that when I export as a png or tiff the code seems to shift text boxes around; i.e. my axis labels and an additional text box I added to the figure are in different locations than I explicitly set in the code and how they appear in the MATLAB figure (R2011a Student Version).

Aaron True

Jesper

maryam

She

Solve my problem puzzled me for a long time, because I can't print *.jpeg files as the figures, and I used to copy *.fig files to another Windows computer to finish printing wanted picutres.
When I get this function, Matlab under Linux is becoming more amazing!

Thank you very much!

Sid

Manuel

Robert McHugh

Austin Fite

The output is beautiful, thank you very much for taking the time to make this.

Sean

Chuntao Dan

Must-have for everyone! Superb figure quality! For Mac users, ghostscript can be installed as a component of the MacTeX-Additions package at http://tug.org/mactex/morepackages.html.

Jamie Guggenheim

ANAND SARIT

pdftops.exe is not running on my system. i have a windows 8 operating system... someone please help..

Lars

This is a great function!
After changing to another linux mint 15 (MATE) from Fedora 18 I get the error message bellow. Do anyone of you have an idea of how to fix it? I tried the fix of Jannik from June 26 2013 without any luck...

Error using eps2pdf (line 107)
Error: /undefined in /findfont
Operand stack:
120 Helvetica ISOLatin1Encoding Helvetica Helvetica
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval--
--nostringval-- --nostringval-- false 1 %stopped_push 1916 1 3 %oparray_pop 1915 1 3 %oparray_pop
--nostringval-- 1899 1 3 %oparray_pop 1787 1 3 %oparray_pop --nostringval-- %errorexec_pop .runexec2
--nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- 1868
5 5 %oparray_pop
Dictionary stack:
--dict:1179/1684(ro)(G)-- --dict:0/20(G)-- --dict:82/200(L)-- --dict:97/160(L)-- --dict:8/95(L)--
Current allocation mode is local
Current file position is 7052
GPL Ghostscript 9.07: Unrecoverable error, exit code 1

Error in export_fig (line 406)
eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);

Lars

Joris Kampman

After having some troubles in Linux Matlab to create nice figures for Libreoffice, this tooling works perfectly!

thumbs up!

Oliver Woodford

Jonne: There is no known issue with thick lines. For example,
>> plot(rand(3), 'LineWidth', 4);
>> export_fig test -png -pdf
works as expected on my PC.

Jonne

Thank you for this function. I use it alot.

Currently I am trying to use it for an plot which contains line plots with 'LineWidth'> 2. The problem is that 'export_fig' won't export lines with fatter lines.

I am wondering if this is a known problem and if there are any solutions to that?

Khoa Tran

I use this script in conjunction with your files to produce graph for journal paper. Excellent work, thank you!

%% Resize graph
w = 0.5;h = 0.5; % this is good for double column format
f=gcf;undock(f)
w=round(w*1050);h=round(h*500);
size=[0 0 w h];
set(f,'Units','pixels','Position',size);

%% Printing
r=300;
[name, path] = uiputfile({'*.pdf','PDF';'*.eps','Vector based .eps';'*.jpg;*.tif;*.png;*.gif','All Image Files';'*.*','All Files' },'Save Image','/Users/Eric/Dropbox/Reports/');
export_fig(fullfile(path,name),f,'-a1',['-r',num2str(r)]);%, '-grey','-nocrop'

Carl Esben Poulsen

Excellent work!

Oliver Woodford

Edison: Set the figure width to 17.3cm, and set the output dpi using the -r300 option in the call to export_fig. If that figure is still too large for your screen, then halve the figure size and double the resolution. If you want the tiff width to say 17.3cm in this case then output the bitmap as an argument from export_fig, and save it yourself using imwrite (setting the 'Resolution' option to 300).

Edison

An essential addition to MATLAB, they should include this as standard in future releases. Great.

One question: does export_fig always use the dimensions of the onscreen figure as a guide? For example, I want to export my figure as a TIFF at 300dpi, with a width of 17.3cm. This equates to an image 2049 pixels wide, and this will not fit on my screen. Thanks for the help.

Emma

Thank you thank you thank you!!!

Saulo Meirelles

Zielinski Christelle

Michael

Thank you for a great program. It perfectly reproduces complex 2D figures that I could not accurately reproduce using any other method.

Ian

Remco Huizenga

First of all: many thanks for an amazing tool and all the work you have put in it. It is very much appreciated.

I do have, however, a small question:
I'm trying to export a plot of a uniform distribution between, say, a and b, to the .png format. This obviously means that the function is zero for values lower than a and higher than b. In that case, the function gets overlapped by the axis and is therefore not visible in the exported .png. It is in the MatLab figure. Am I missing something or is there a fix for this? Thanks in advance

Jaap de Vries

I got it fixed, code works great!!
When I set the background transparent the part inside the graph remains white, while the sections outside the axis become transparent, any tips?

Regards,

Jaap

Oliver Woodford

Jaap: sounds like you're shadowing MATLAB's print() with another function of the same name.

Jaap de Vries

Error using print
Too many input arguments.

Jaap de Vries

I am really looking forward to using this code but I keep getting the following error...

export_fig 'test.jpg'

Error in print2array (line 140)
print(fig, renderer, res_str, '-dtiff', tmp_nam);

Any help would be apreciated.

Regards, Jaap

Junghwan

Werner

you just saved my thesis…

pr

zhu

good

LDELBENE

Amazing, but it does not work with transparent surf plots for eps or pdf files.

Arttu Modig

Thanks a lot Johannes for the Mac OSX dylib fix!

Zhiyong

BERDIN

J.R.! Menzinger

A very useful tool, thanks.

Agnethe

Matlab2010

Long time user of export_fig here. great function -- thanks!

New machine today. 64 bit Windows 8.1, MATLAB 2013B. Latest installation of Ghoscript (9.1) put onto the machine.

A problem occurs with the function ghostscript.m

On executing the code in this m file: check_gs_path(path) a zero is returned.

This causes the software to ask where the location of the ghostscript executable is -- i point it to the correct dir and it fails to find it.

Thus I have had to hard code in

path = 'C:\Program Files\gs\gs9.10\bin\gswin64c.exe';

before check_gs_path(path) is called, which works.

What's going on?

Thanks

Alexander

Many thanks. Before find this I was wasting so much time copying the images and then trimming

Antoine Liutkus

great, did it whereas matlab could not =) thanks

Bill

Hi, Oliver,
How can I use it to export .emf files? Is it possible ?

Marco

I used export_fig in a GUI. Anyone who wishes to create a button that saves specific figures to specific locations on their PC, feel free to use the code below (where PLOTTAG is the plot's tag in plot properties):

[file,path] = uiputfile({'*.eps';'*.pdf';'*.png';'*.jpg'},'Save Figure As');

if file ~= 0
%Gets the size of the file name
[empty,filechar]=size(file);
%Deletes the file type from teh end of the file name and stores it
filetype(3) = file(filechar);
filetype(2) = file(filechar-1);
filetype(1) = file(filechar-2);
file(filechar) = [];
file(filechar-1) = [];
file(filechar-2) = [];
file(filechar-3) = [];

%Runs the export_fig command with the path and file name, along with the
%filetype
export_fig(findobj('Tag','PLOTTAG'),[path,file],['-',filetype]);

%Message box
h = msgbox({'Done!';'';...
['The file ',file,'.',filetype,' can be found in:'];path},...
'Save Figure File','none','modal');
elseif isempty(file) == 0
h = msgbox('Not saved.',...
'Save Figure File','none','modal');
end

Will Grant

I am using figures with contour lines, thus my figures are: axes > contourgroup > patch objects.

In my exported images, I was getting the axes with all text label objects but no lines.

I had to change line 97 in isolate_axes.m from allchild() to findall() as a fix. I don't know if this breaks anything but it shouldn't as findall just finds all objects lower in the hierarchy than the one passed in, which is the axes handle in this case. I was losing the patch objects that make up the figure as allchild() was only returning the objects at the first level under the axes.

Will

DQ Zhang

Great!

BTW, how to set the resolution?

Dun Kirk

I got this warning using export_fig(axes_handle):

Warning: Callback for uicontrol of style radiobutton will be overwritten when added to a UIBUTTONGROUP.
Use the SelectionChangeFcn property on the button group instead.
In copyfig at 25
In isolate_axes at 52
In export_fig at 181

Peter

Hi Oliver and all,

I used your script quite a lot to make png's. For some reason I get different output ratios, depending on the x and ylabel? (Which is driving me crazy...) I am not sure what I am doing wrong. The effect does not appear with the Matlab print function... but the png is as expected not as nice. Anyone an idea?

Jack

Sebastian

Leah

Worked perfect! Very easy to use. Make sure you close the pdf file you are writing to or you will get a GS error.

Oliver Woodford

Sanka: I suspect this has nothing to do with export_fig and everything to do with the software you're using to view the eps file.

Lennart: You can set the default background color for MATLAB figures, outside of export_fig. There is no 'transparent' option, but the help text does mention a '-transparent' option.

Lennart

Great tool!
However, I wish to export to a pdf with a white background. Then I have to do 'set(gcf, 'Color', 'w');' every time. Is there a permanent setting or a parameter that can be set?
This does not seem to work: export_fig(fig_handle,'figure.pdf', 'transparent' )

dong

Sanka

Hi Oliver,

Great file, really should come as standard with MATLAB! Just one issue I am having when exporting to .eps format. All text in the figure (axes numbers and legend text) are being outputted in bold. This is not the case for every other file format such as pdf or tiff, where the figure appears exactly as it does on screen. Any idea why this is happening specifically to eps??

Thanks

Fernando

James

I just started using this. I mostly only use HG2.
I get the following error when I try to run your example code for creating a .pdf, with HG2.

B = randn(ceil(size(A, 1)/6), ceil(size(A, 2)/6), 3) * 0.1;
B = cat(3, kron(B(:,:,1), ones(6)), kron(B(:,:,2), ones(6)), kron(B(:,:,3), ones(6)));
B = A + B(1:size(A, 1),1:size(A, 2),:);
imshow(B)
>> export_fig test.pdf
Error using eps2pdf (line 107)
Error: /undefined in bdef
Operand stack:
dom --nostringval--
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push
--nostringval-- --nostringval-- --nostringval-- false 1 %stopped_push 1932 1 3
%oparray_pop 1931 1 3 %oparray_pop 1915 1 3 %oparray_pop 1803 1 3 %oparray_pop
--nostringval-- %errorexec_pop .runexec2 --nostringval-- --nostringval-- --nostringval-- 2
%stopped_push --nostringval--
Dictionary stack:
--dict:1190/1684(ro)(G)-- --dict:0/20(G)-- --dict:77/200(L)--
Current allocation mode is local
Current file position is 64
GPL Ghostscript 9.10: Unrecoverable error, exit code 1

Error in export_fig (line 431)
eps2pdf(tmp_nam, pdf_nam, 1, options.append, options.colourspace==2, options.quality);

I do not get this error when I am not using HG2, but it would take awhile for me to convert everything back from HG2. Do you have any ideas how to fix the problem?

(Note, laprint also doesn't seem to work with HG2. So, this could be a problem with HG2 and not have anything to do with your files.)

Oliver Woodford

David: The grid lines are the width specified (by setting the axes line width), but the segments are shorter (there's no option to change this). Try using thicker grid lines.

David

Excellent work, many thanks! Question though, I'm finding that when printing, the only objects not reproduced "as shown" are the gridlines. The output gridlines are much fainter and barely visible. Any way to address this? Thanks!

Manuel

Mikolaj Magnuski

Mikolaj Magnuski

max, does it work if you try:

export_fig('/Users/maxnorris/Desktop/test.png',H);
or:
export_fig('/Users/maxnorris/Desktop/test','-png',H);

?

max

Oliver,

I have just downloaded your code and it seems to be receiving great reviews. I can't seem to get it to work though... All i want to do is to save a figure window to my desktop.

I have a figure that is displaying an image. How would I use export_fig to save this figure under the name 'test' in png format?

This is what I am seeing: (H is set to be the figure handle)

>>export_fig('/Users/maxnorris/Desktop/test','png',H)
Error using print
Too many input arguments.

Error in print2array (line 140)
print(fig, renderer, res_str, '-dtiff', tmp_nam);

Error in export_fig (line 334)
[A, tcol] = print2array(fig, magnify, renderer);

Jeff

Awesome work!! It is so much better than the Matlab default export system. Thank you very much for creating this great function for us.

Kirsten

Ozan Oguz

I said I am using "uicomponent" for my GUI.

Actually, I am using " "GUI Layout Toolbox".

I am sorry for the misinforming.

Ozan Oguz

I realised something:

I am using "uicomponent" for my GUI.
After giving "print" command (export_fig),my GUI changes.

What changes exactly?

1) All "uiextras.Empty" objects seem to vanish.

2) Legend in the axes becomes uneditable.

For now, this is what I observed.

Ozan Oguz

This seems to be a great app, thx!

I have a question/problem:

I designed a GUI using uicomponent.m from file exchange. Left part is for controls, right part is for axes.

When I try to export the image of this axes, two different things happen for bitmap and vector formats. 1) For pdf, it gives me only the axes, and this is what I want, but 2) For png or jpg, it also gives me the empty area behind the control buttons on the left side of the axes.

I want a bitmap image with only the axes. Nothing more.

Can you help me, please, Oliver?

WurmD

Hi Oliver,
Let me add my voiceto the chorus: "Fantastic work!" :)

Now, I notice one thing you change is the grid lines to "- Improved line and grid line styles"
Which in my plot have been "No grid lines"

It would be nice to have the option of keeping the grid lines as shown, and keep your "Improved line and grid lines" as default

I looked into the code but couldn't figure where you're not adding the grid lines to the pdf

Will you create such an option (keep grid lines)? Will you tell me how?

Cheers!

Wonderful performance with fast help from Oliver as if online talk! Save memory and run-time with '-a1' option while keeping quality as plotted, applying it as follows:
set(gcf,'color','w')
export_fig(filename,'-png','-a1','-nocrop')

Oliver Woodford

Tim: You're missing the -nocrop option.

Tim Garrett

Terrific function, but I am unclear on one thing. I wish to create a little booklet of figures where the page size and axis locations are precisely defined. e.g.
h = figure;
set(h,'units','inches','position',[0 0 8.5 11]);

plot(x,y);
set(gca,'Position',[0.2, 0.2, 0.6, 0.6];

Using 'print', my printed figure is placed exactly where I want within the page I want (albeit with stupid matlab problems). With 'export_fig' however, the output is *only* of the figure. The figure is not within a page.

What am I missing?

Thanks.

Edgar Goederer

Ivo

finally... Fantastic, thanks!

Alex R.

Great package. You can safely detect Ghostscript under Windows by reading the registry key "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Artifex\GPL Ghostscript" (if 64bit) or "HKEY_LOCAL_MACHINE\SOFTWARE\Artifex\GPL Ghostscript" (if 32bit).

Use Matlab's winqueryreg() function or execute "reg" via system() to read the Windows registry.

Keep up the good work!

Yuanwei

Great tool. Exactly what I am looking for.

Q: when I export 1080p pic, it gives me a 1921x1081 pic in the saved jpeg. Any thought? Thanks

Koen

powerful and easy to use. Png output is fine for transparent patches if you set the resolution at a decent level.

Tomasz

Andrew Bazyk

Ali Abolfathi

George

Dear Oliver,
thank you for this helpful function. In general, it workds fine. But when there are more than one font types are not in the matlab_fonts list, the function will give error :
Error in print2eps (line 97)
font_swap{3,a} = fonts{font_swap{1,end}(1)};

it seems that the equation should be:
font_swap{3,a} = fonts{font_swap{1,a}(1)};

BTW, do you know how to use font types which are not in matlab_fonts list, e.x. Garamond, Palatino Linotype?

thank you.
George

Oliver Woodford

Igor: You cannot specify the screen resolution in a call to export_fig. However, you can specify your figure size in units that are independent of pixel pitch, such as 'cm'. I suggest you try that.

Igor

Great script.
A question: how can I specify screen resolution while saving figure as .eps?
At the moment, the use of print2eps for the same figure gives different results (different scales) on computers with different screen resolutions (Matlab 2012a x64, Win7 x64 on both of them).

luke

Shicai Yang

Sam

Jannik fix works for the Issue I had (reported on 18 Jun 2013) using ubuntu 13.04 running Matlab R2012b.

Thanks Jannik. Really helped me out.

Jannik

I also get a ghostscript error:

Error: /undefined in --definefont--
Operand stack:
mwa_cmmi10 --dict:11/20(L)-- Font definefont --dict:30/32(L)-- unknownerror
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2
%stopped_push --nostringval-- --nostringval-- --nostringval-- false 1
%stopped_push 1900 1 3 %oparray_pop 1899 1 3 %oparray_pop --nostringval--
1883 1 3 %oparray_pop 1771 1 3 %oparray_pop --nostringval--
%errorexec_pop .runexec2 --nostringval-- --nostringval-- --nostringval-- 2
%stopped_push --nostringval-- 1762 2 3 %oparray_pop --nostringval--
--nostringval-- 1850 2 4 %oparray_pop --nostringval--
Dictionary stack:
--dict:1173/1684(ro)(G)-- --dict:0/20(G)-- --dict:82/200(L)--
--dict:1173/1684(ro)(G)--
Current allocation mode is local
Last OS error: No such file or directory
GPL Ghostscript 9.07: Unrecoverable error, exit code 1

when using export_fig with Matlab 2013a and ArchLinux.
I solved this issue by clearing the LD_LIBRARY_PATH enviroment variable before executing gs by replacing

system(sprintf('"%s" %s', gs_path, cmd));

with

system(sprintf('export LD_LIBRARY_PATH=""; "%s" %s', gs_path, cmd));

in the ghostscript.m file. Maybe this will help in case of other ghostscript issues as well.

Sanka

Brilliant script. Some much time is saved by avoiding the post-processing I used to do to get publication quality figures/images.

Sam

Great script but I updated my linux machine and now I am getting the following error. Any Ideas??

Error: /undefined in /findfont
Operand stack:
120 Helvetica ISOLatin1Encoding Helvetica Helvetica
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- false 1 %stopped_push 1916 1 3 %oparray_pop 1915 1 3 %oparray_pop --nostringval-- 1899 1 3 %oparray_pop 1787 1 3 %oparray_pop --nostringval-- %errorexec_pop .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- 1868 5 5 %oparray_pop
Dictionary stack:
--dict:1180/1684(ro)(G)-- --dict:0/20(G)-- --dict:82/200(L)-- --dict:97/160(L)-- --dict:9/85(L)--
Current allocation mode is local
Current file position is 10662
GPL Ghostscript 9.07: Unrecoverable error, exit code 1

Error in print2array (line 95)

Error in export_fig (line 327)
[A tcol] = print2array(fig, magnify, renderer);

Oliver Woodford

Nicky: That's difficult to fix in export_fig. However, a workaround is to draw the grid lines or the axis bounding box manually to be able to get the desired ordering.

Nicky

I want to export a figure to a .png and I want my linetypes and gridlines to be scaled correctly, so I've got to use the 'painters' renderer. The axis border ('box') is exported under the plot which means it gets covered by the plotted points. This does not happen with the default renderer.
If I change the axes layer to 'top' then the border comes to the top but so do the gridlines. Is there a way of having only the axes border at the top but not the gridlines?

Thanks for the script Oliver... been using it for a long time now and it fills a big gap in MATLAB.

xg

Very useful

Oliver Woodford

m_user: You can export a particular axes in a figure just by passing in a handle, but there is no support for rendering just part of an axes - I do not intend to implement this either. I suggest you use the newsgroup or Answers to find out the many other ways in which you might achieve what you want.

m_user

Hi Oliver, "short" question: I built a GUI with a handles.axes in which a greyscale image is in the background and a colored, semitransparent image is in the foreground. Now I want to save this overlayed image but I have no variable which "points" to that overlay (so I can't write export_fig Test.fig). Is there another way (e.g. write export_fig gca..) to reference on the handles.axes? thanks in advance..

Anthi

Thanks Oliver.i am a beginner at programming.your function is great.

Oliver Woodford

Derek: The current version fixes this.

Anthi: In the example export_fig('C:/Users/Me/Documents/figures/myfig'), "myfig" IS the name.

Derek

After upgrading to 2013a, I get an error when using export_fig to save a .png with a transparent background. It works fine in 2012a. Perhaps Matlab changed something about writepng in 2013a? Has anyone found a work around for this? Is there an updated version of export_fig that can save a .png with a transparent background in 2013a?

export_fig CouplingEfficiency.png -transparent -native
Error using writepng (line 78)
Argument 'alpha' failed validation with error:
Expected input to be one of these types:

double, uint8, uint16

Error in imwrite (line 473)
feval(fmt_s.write, data, map, filename, paramPairs{:});

Error in export_fig (line 281)
imwrite(A, [options.name '.png'], 'Alpha', alpha, 'ResolutionUnit', 'meter', 'XResolution',
res, 'YResolution', res);

Andriy Nych

Daniela Soto

Anthi

Great functions!Thanks Oliver.
i have a question.How can i export to a specific directory with a specific name?

For a name :
>> export_fig Alex

For a directory:

>>export_fig('C:/Users/Me/Documents/figures/myfig')

but how can i combine them?

Ian

kamel

François

Awesome script! Works perfectly under Windows, but I have trouble to make it work with my Linux installation.
Here is the error returned:

Error using eps2pdf (line 107)
gs: /usr/local/share/matlab/R2013a/bin/glnxa64/libtiff.so.5: no version information available (required by /usr/lib/libgs.so.9)
Error: /undefined in /findfont
Operand stack:
96 Helvetica ISOLatin1Encoding Helvetica Helvetica
Execution stack:
%interp_exit .runexec2 --nostringval-- --nostringval-- --nostringval-- 2 %stopped_push --nostringval-- --nostringval--
--nostringval-- false 1 %stopped_push 1916 1 3 %oparray_pop 1915 1 3 %oparray_pop --nostringval-- 1899 1 3
%oparray_pop 1787 1 3 %oparray_pop --nostringval-- %errorexec_pop .runexec2 --nostringval-- --nostringval--
--nostringval-- 2 %stopped_push --nostringval-- --nostringval-- --nostringval-- 1868 5 5 %oparray_pop
Dictionary stack:
--dict:1179/1684(ro)(G)-- --dict:0/20(G)-- --dict:82/200(L)-- --dict:97/160(L)-- --dict:8/89(L)--
Current allocation mode is local
Current file position is 7119
GPL Ghostscript 9.07: Unrecoverable error, exit code 1

What is happening?

Iman Ansari

Oliver Woodford

arnold: I didn't. Please don't take my suggestion the wrong way :). Try ConvertPlot4Publication.

arnold

Please don't get it the wrong way :)
I'll create a script of my own combining it with 'fig' for instance.
I only meant well, your script is great as it is ;)

Oliver Woodford

arnold: The goal of export_fig is to export what is on screen. By all means write a script that makes your figure the right size, have the correct line widths, fonts, etc., then calls export_fig with the correct resolution. Or use one of the several submissions that already do this.

arnold

Hi,
I've got another proposition: rescale figure

To make 'export_fig' even more useful for publications it'd be awesome if you added the possibility to rescale the figure to a certain size.
example:

export_fig 'test.png' -w5 -h4 -r300

This would set the width to 5" and the height to 4" and then export at 300dpi.
For us non-americans it'd be great if you added size in metric units [cm] as well.

export_fig 'test.png' -wm5 -hm4 -r300

would then set the width to 5cm etc.

Falko Schindler

Siyi Deng

IMO this should be built in into matlab releases.

Iman Ansari

Mingyao

Hello Oliver, I have noticed that cropping does not always happen for a figure with an array of, say, 5 by 5 subplots. It leaves the margins on the left, top, and right sides of a figure as they are while cropping out the bottom margin. How should I address this? Thanks a lot!

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.

Greg

Greg

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.

Oliver Woodford

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

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/"

Wouter

Use this submission daily. Should be incorporated in Matlab!

yuhua zou

Great! It provides what I need!

Viktar Tatsiankou

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.

arnold

Laura

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

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

Wouter

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.

Sauro Salomoni

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

Max

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

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...

Ali Hummos

Outstanding!

Arindam Bose

Max

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!

Damjan Miklic

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

guo

thx very much. very useful and enlightening!

Yan Jiang

A must have for scientific researchers!

Salman Mashayekh

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

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:

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!

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

RP

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.

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.

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

Bahaa

RP

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.

University Dschang

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

Jonathan

Anoosha papireddy

zhr

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

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.

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

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!

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?

Long Nguyen

Nitin

Alan Chen

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!

Cahaya

MikeStein

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')

Juan Cardelino

Malcolm Hudson

John

Great script, thanks for your work!

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.

Olivier

Karl

twimmeh

dbdq

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

dbdq

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

Kami

Kami

Laurent

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.

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?

Rodolphe

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

Will Fonseca

Found the solution of my question ans extra help in:

Michal Ficek

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

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.

Will Fonseca

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.

Sandrine

Ratan

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')

Jessica Lam

Ileana

JR King

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

Thanks

Ryan

Well done - robust, continually updated and works great!

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.

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.

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.

Alexander Farley

Works as expected first try.

Fabio Gori

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

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

rito

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

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

Javier

Hi,

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

Thank you

Mathieu

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

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.

Haonan Chen

good job

Hin Kwan Wong

Hin Kwan Wong

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

Antoine C

Thanks a lot for sharing that powerfull founction.

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

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.

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

Oliver Woodford

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

Matlab2010

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

Scott Otterson

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.

sam p

Great job.!!

John Reinert Nash

Estee

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!

Andrey

Bosheng

I like the transparency!!

Yuri K

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.)

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).

Yuri K

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

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.

Blake Richards

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.

Bijesh

thanks a lot!

Igor

Kiron

Great work!

Excellent. This has worked wonders for my PowerPoint presentations.

Wonsang You

Jinwei Gu

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.

Giorgio

Ken Campbell

Oliver was extremely helpful when I contacted him with a question. His page

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.

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.

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)

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.

Kemal

Needless to say the Matlab functions don't work.

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!

Zoe Zhang

Petteri T

Darren Price

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

Ingo

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).

Renwen Lin

v good!

Xin

Very useful package to export beautiful figures.

Nathan Tomlin

Sebastien PARIS

Ankur Pawar

Very useful function.

Chris

This is great.

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

Thanks

Rene

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

Rene

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!

owr

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

Anuj

pietro

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

Cameron Sparr

Son Hua

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.

Sam Hallman

Onkar Singh Gujral

very good

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:

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.

Erika

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.

Shaun

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

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.

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

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.

Ole

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

David Wang

Peter T. S. DeVore

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

Peter T. S. DeVore

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

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.

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

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!

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.

Jiaqi

weijie

You save me thesis!

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.

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?

Patrick Maletinsky

Sébastien

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.

Oliver Woodford

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

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.

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.

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.

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.

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!

Oliver Woodford

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

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?

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.

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.

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

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.

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

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.

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.

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?

Emily

Sherif

Very useful. Thank you.

Céldor

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.

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).

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.

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.

A

This is the most wonderful program! Thank you :)

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.

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.

Shiguo

nsbd

Matthijs Klomp

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!!!

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');

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.

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.

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.

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?

Liang Zhan

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

Martin

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

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

Oliver Woodford

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

Oliver Woodford

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

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

Martin

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.

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!

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.

Oleg Komarov

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

Oliver Woodford

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

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.

Oliver Woodford

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

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.

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.

Image Analyst

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

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.

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?

Reinhard

Elsa Birch

Many thanks!

Joseph LIM

Rossella

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

Great work!

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

mathworks2011

Julia

Dear Oliver,

thanks for saving my (publication) life.

Julia

Oliver Woodford

Craig: Nice observation. Done.

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.

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.

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.

Matthijs Klomp

I have used print_pdf for all my publications.

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.

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!

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!

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 :)

Vinesh Rajpaul

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

Vinesh Rajpaul

Matthew Arthington

Mark

Joseph

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!

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

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!

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!

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.

Daniel

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.

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.

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!

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.

Jared

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

Very useful, thanks.

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?

Glenn Fulford

zhuhhu

very useful. simpler use with respect to the laprint

Glenn Fulford

Shai Sabbah

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

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.

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

Roland

Michael Johnston

Extremely useful.

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.

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

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.

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
uiwait(wh)
end

Jean-Baptiste Carré

Oliver Woodford

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

xtofe xtofe

very useful it is indeed.

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

Any ideas??

Very useful fix for missing functionality within Matlab.

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.

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.

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?

yep,it worked well.thanks again

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');

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))

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.

Yvonne Haesevoets

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

Xuezhong Wang

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).

Yvonne Haesevoets

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

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.

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.

Oliver Woodford

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

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.

Bob

Keely Willis

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

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!

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".

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.

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.

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?

Francesco Montorsi

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.

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!

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"

thanks,

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!

68c46a6

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

cartonn

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

Sebastiaan