MathPSfrag 2: Convenient LaTeX Labels in Mathematica

01/15/2008 ∙ by Johannes Große, et al. ∙ Jagiellonian University 0

This article introduces the next version of MathPSfrag. MathPSfrag is a Mathematica package that during export automatically replaces all expressions in a plot by corresponding LaTeX commands. The new version can also produce LaTeX independent images; e.g., PDF files for inclusion in pdfLaTeX. Moreover from these files a preview is generated and shown within Mathematica.



There are no comments yet.


page 1

page 2

page 3

page 4

This week in AI

Get the week's most popular data science and artificial intelligence research sent straight to your inbox every Saturday.


Many programs producing EPS graphics do not allow the inclusion of LaTeX commands. While there exist several solutions to work around these difficulties, they all have various drawbacks. (See McKay:1999 for a discussion of several methods and an alternative approach to overcome these difficulties.) In this article, we will focus on a particular existing solution, the PSfrag package Grant:1998 , which provides LaTeX macros allowing the user to replace pieces of text (“tags”) in an EPS file by an arbitrary LaTeX construct.

However, for PSfrag to work, the application must write tags unaltered into the EPS file. For Mathematica Wolfram:1999book ; Wolfram:2005mathematica , this requirement amounts to using single words, strictly consisting of alphanumeric characters only. As a consequence, the user has to work most of the time with an inconveniently labeled graphic and is furthermore required to keep track of the tags used in the substitution macros.

On the other hand, it is not always possible to use Mathematica’s conventional export function as it produces EPS files requiring the inclusion of additional fonts into the document. This means configuring the local TeX installation such that it finds the fonts provided by Wolfram Inc. WRI:tetex ; WRI:gsfont ; WRI:intoeps , a process often not being under the author’s control. A way out is to include the fonts into the EPS file and set the font family to a standard PostScript one. The required steps are version dependent— the latest version as of this writing, 6.0, has sane defaults—for 5.2, the following commands are required: [commandchars=
()] Plot[…, TextStyleFontFamily"Times"] Export[…, ConversionOptions "IncludeSpecialFonts"()True] However, automatic inclusion of Mathematica’s special fonts, which irrespective of the chosen FontFamily are used for displaying important symbols like brackets, is only a last resort. While the slight mismatch between a standard PostScript font’s appearance, (here Times Roman, cf. fig. LABEL:fig:poor), and that of LaTeX’s standard font (Computer Modern) may be acceptable in case of ordinary text labels, mathematical expressions like square roots or fractions cannot compete with LaTeX’s typesetting quality in this approach.

Figure 1: Old vs. new graphics export mechanism.

gA[bc][bc]TeX *gA[cc][bc] tag[bc][bc]tag *tag[cc][bc] tag[bc][bc]tag *tag[bc][bc]TeX *tag[cc][bc] *tag[bc][bc]TeX
a) b) c) d)
Figure 2: Action of \psfrag{tag}[bc][bc]{\TeX}. The first coordinate pair [bc] picks the reference point (red crossed circle) in the TeX expression (fig. a), the second one in the tag that is part of the original EPS file (fig. b). Positioning is achieved by overlaying both boxes such that their respective reference points coincide (fig. c). The final result is shown in fig. d. Scales are exaggerated for better illustration.

Font inclusion is also a feature that—like the visually displeasing option to not use special fonts at all—has become available only starting from Mathematica version 4.2.1. Consequently, some authors simply restrict labeling of Mathematica plots to a bare minimum.

MathPSfrag Grosse:2005 is a package that conveniently produces publication-quality labels in EPS files generated by Mathematica. MathPSfrag automates many (often all) tedious details related to the use of the standard LaTeX package PSfrag, while still allowing manual fine tuning. As a demonstration of the degree of automation, compare fig. LABEL:fig:poor, which has been generated by using the standard Mathematica command Export, and fig. LABEL:fig:beautiful, generated by MathPSfrag’s export instruction.

While the solution presented here, relies on the PSfrag package, it avoids many of its shortcomings by providing a semi-automatic layer. In many cases it is sufficient to simply use the new PSfragExport command.

MathPSfrag also allows the creation of stand-alone images that do not need any additional preparations in the manuscript. This is achieved by calling LaTeX and Ghostscript from within Mathematica requiring the user to have a full LaTeX distribution on the same machine where Mathematica resides.

The first section of this document describes the PSfrag LaTeX package, while the second and third section explain its counterpart MathPSfrag. A number of small examples are shown followed by a discussion of how to produce PDF files. Before the conclusions, a few limitations of the current approach and its implementation are discussed.

I PSfrag

This is intended to be a short introduction to the LaTeX package PSfrag explaining only the essential features necessary to understand the corresponding Mathematica package’s internals and to take advantage of its manual options if automatic placement does not yield the desired result. The full documentation can be found in Grant:1998 .

PSfrag provides the macro [commandchars=
()] \(psfrag)(tag)[(texposition)][(psposition)] [(scale)][(rot)]((LaTeX)) which replaces any occurrence of tag in the output of an EPS file by LaTeX. According to Grant:1998 , “all \psfrag calls that precede an \includegraphics (or equivalent) in the same or surrounding environments” will affect the output of the included graphics; i.e., \psfrag commands can be defined either locally, to act on strictly one graphic, or globally, thus acting on all graphics in a document. The mechanism is demonstrated in fig. 2.

gA[br][br]—[br][br]— *gA[Br][bc]—[Br][bc]— *gA[cr][bl]—[cr][bl]— *gA[tr][Bl]—[tr][Bl]— *gA[bc][Bc]—[bc][Bc]— *gA[Bc][Br]—[Bc][Br]— *gA[cc][cr]—[cc][cr]— *gA[tc][cc][0.75][45]—[tc][cc][0.75][45]— *gA[bl][cl][1.5][30]—[bl][cl][1.5][30]— *gA[Bl][tl]—[Bl][tl]— *gA[bl][Bl]     (baseline) *gA[bl][cl]     (center line) *gA[bl][tc][1][-90]     (center line) *gA[cl][tc]—[cl][tc]— *gA[tl][tr][1][180]—[tl][tr][1][180]—

Figure 3: Illustration of the various optional arguments of the \psfrag command, taken from Grant:1998 with minor changes. The first option determines the alignment of the LaTeX description, while the second one is responsible for the point to which the LaTeX macro is attached.

texposition and psposition are optional arguments that allow setting (first) the vertical (top, bottom, Baseline, or center) and (second) the horizontal (left, right, center) alignment of the replacement text by specifying the respective first character of the choices given in parentheses. The arguments refer to the position of the reference point in the respective bounding boxes. The LaTeX construct is placed such that its reference point is at the position of the corresponding PostScript (tag) box’ reference point, cf. fig. 3.

scale and rot permit scaling and rotation of the inserted box, where the rotation (in degree) is relative to the slope of the PostScript bounding box such that a value of “0” preserves the orientation, see fig. 7. Scaling is best achieved by using LaTeX scaling commands, like \Large, instead of the scale option, since the standard LaTeX fonts consists of bitmaps rendered specifically for the chosen size and do not rescale well.

Since PSfrag exchanges the labels of an EPS image, these may protrude from the bounding box of the resulting image. Fortunately, \includegraphics offers the options bb and trim, which may be used to override or correct the obsoleted information in the EPS file. In particular, in conjunction with some of the PDF production techniques described in subsequent sections, correct(ed) bounding boxes can be important because protruding material might be clipped.

Ii MathPSfrag

There are only three commands needed to control MathPSfrag’s EPS generation: PSfragExport, which supersedes Mathematica’s Export command, and PSfrag, which allows overriding of the defaults for particular expressions. In addition the UnPSfrag command is provided which calls LaTeX and Ghostscript to carry out the PSfrag replacements and create an (ordinary) EPS and PDF image that can be included with the usual \includegraphics command.

The export function is usually called in conjunction with UnPSfrag: [commandchars=
()] PSfragExport[(basename), (graphics), (options)] // UnPSfrag; This converts graphics, the usual Graphics construct returned by Mathematica commands like Plot, to an EPS file and a LaTeX file containing \psfrag macros. The UnPSfrag command, if provided, will merge these two into a single EPS file and will also produce a PDF version. More about this in section III.

There are a number of options for PSfragExport that can be used to override internal assumptions about the automatic processing of graphics. They are documented in the manual accompanying MathPSfrag. The respective file names of the LaTeX and EPS file are determined by basename to which the value of the options TeXSuffix and EpsSuffix is appended.

  • TeXSuffix"string" ("-psfrag.tex")

  • EpsSuffix"string" ("-psfrag.eps")

Unless a base name containing a path is given, the output is written to the current directory, which can be set using Mathematica’s SetDirectory. Unknown options are passed on to the graphics using a Show command.

It may happen that the user is not satisfied with the automatic output generated by PSfragExport. Therefore it is possible to manually control the replacement of any expression by wrapping [commandchars=
()] PSfrag[(expr), (options)] directly around any Mathematica expression expr appearing as text in a graphic, such as the argument of a PlotLabel... or AxesLabel... option or a Text graphics directive. As a simple example, consider [commandchars=
()] p=Plot[…,PlotLabel()PSfrag["^2-test", TeXCommand()"-test"]]; PSfragExport["chisquare", p]; This is also the simplest possibility to correct malformed automatically generated LaTeX code.

PSfrag processes the following options, whose defaults have been put in parentheses.

  • TeXCommand"string" (Automatic)

  • PSfragTag"string" (Automatic)

  • TeXPosition"yx" (Automatic)

  • PSPosition"yx" (CopyTeXPosition)

  • PSRotationnumber (0)

  • PSScalingnumber (1)

  • TeXShiftX"texdim" (0pt)

  • TeXShiftY"texdim" (0pt)

Actually, PSfragExport’s automatic mechanism basically wraps PSfrag around all Text primitives using the default values above. However, manual wrapping has the advantage of allowing different options to be applied to expressions where the automatic behavior did not give satisfactory results.

TeXCommand"string" uses string as the LaTeX command to appear in the final EPS graphic as a replacement of the corresponding expression expr. If set to Automatic, the internal function GuessTeX is called, which is essentially a wrapper for TeXForm that adds $ signs around math expressions. The options PSfragTag, TeXPosition, PSPosition, PSRotation and PSScaling are in one-to-one correspondence to the options of \psfrag explained in the previous section.

As a last resort TeXShiftX/Y provide a way to move the LaTeX expression by a specified TeX dimension. A disadvantage of this method is that it does not scale with the image dimensions.

Unless the user provides specific values, MathPSfrag uses the FullGraphics command to determine the arguments for TeXPosition and PSPosition.

Unfortunately FullGraphics does not work for three-dimensional graphics, such that PSfragExport falls back to PSfragManualExport, which does not perform any alignment detection and can also be used for two-dimensional graphics if automatic processing is not desired. In these cases PSfrag has to be applied by hand to the argument of any Text directive and text producing option like PlotLabel. Moreover at least the values of TeXPosition will have to be given by the user.

Since this can be rather cumbersome for explicit tick mark specifications, an additional convenience command has been introduced, [commandchars=
()] PSfragTicks[(tickspec), (options)] which simply applies PSfrag with the provided options to any tick mark label in tickspec. Since the tick mark specification itself is usually quite lengthy, it is recommended to create it with the LinTicks[from, to] command from CustomTicks Caprio:2005 . A three-dimensional plot illustrating this procedure is included as example code; its output is depicted in fig. 4.

[commandchars= ()] Ticks PSfragTicks[LinTicks[-1,1],TeXPosition"Bc"], PSfragTicks[LinTicks[-1,1],TeXPosition"Bl"], PSfragTicks[LinTicks[-1,1],TeXPosition"Br"]

Figure 4: Three dimensional example: As there exists no FullGraphics3D command, manual labeling was preformed by using the above Plot3D option. LinTicks is provided by the CustomTicks package Caprio:2005 .

Iii UnPSfrag

With the commands described so far, standard PSfrag EPS pictures can be produced. MathPSfrag provides two additional features that require a full LaTeX run from within Mathematica. First, creation of pre-rendered EPS images, which do not require the PSfrag package anymore. Such pre-rendered images will be called “unpsfraged” henceforth. Second, conversion to PDF images suitable for pdfLaTeX or raster images providing a preview of the final plot. For both features, MathPSfrag needs to know where to find the executables for LaTeX, dvips and Ghostscript. Unless the binaries are in the system’s execution path (as will be the case for Unix-like operating systems), this requires the user to set the location of the files explicitly. The notebook containing the code of all example plots shown in this article also contains a comprehensive step-by-step guide of how to set up these paths permanently. Detailed explanations can also be found in the manual.

The syntax of UnPSfrag is [commandchars=
()] UnPSfrag[(basename),(epsfile),(texfile),(options)]; where basename is used to create the names of output files by appending suitable suffices like “.pdf” or “.eps”. The other two mandatory parameters should point to the tagged EPS and PSfrag-LaTeX files that are to be merged. PSfragExport returns the three file names in exactly this format such that its output can be directly fed to UnPSfrag.

UnPSfrag has a number of additional options that control how images are created. Again only the most important ones shall be given here, while a complete list is given in the manual.

By default, UnPSfrag only produces an EPS and a PDF file, though it should be possible to generate other output formats by setting the UnPSfragOutputFormats option accordingly.

Furthermore UnPSfrag shows a low resolution bitmap preview of the final images. While this is extremely useful for checking if MathPSfrag has produced the desired results, it will enlarge the notebook considerably, which can be inconvenient for email exchange. Setting the PreviewDevice option to None will switch off this behavior. This option is further discussed in the section on known bugs.

When using the PSfrag option TeXCommand to specify LaTeX code, it might require additional style files. These can be included by UnPSfrag when providing the appropriate \usepackage command as a string via the TeXPreamble option.

IncludeGraphicsOptions is the most important option. The string it provides is handed over to the \includegraphics command in the LaTeX file used to perform the \psfrag replacements. The option can therefore be used to set the size of the rendered graphics; e.g., by setting its value to "width=7cm". Note however that the final bounding box will correctly fit the image content instead of exactly matching the specified size. This mismatch is due to the bounding box changing during PSfrag’s replacement procedure. When an exact size is required, it can be reapplied in the manuscript, though it is better to adjust the size from within Mathematica, the reason for which is explained in the next section.

Iv In the manuscript

UnPSfrag’ed images do not require any additional treatment or package beyond graphics/graphicx. Since EPS and PDF versions are created anyway, it is recommended not to provide any suffix for the file name in the \includegraphics command, such that the manuscript translates with both LaTeX and pdfLaTeX. It is possible to issue the common size options, but this will also change the labels, such that they will not have the fixed TeX sizes anymore. This can potentially reduce the fonts quality, in particular when TeX’s old bitmapped computer modern fonts are used. The UnPSfrag option DvipsOptions is by default set to "-Ppdf", which makes dvips replace bitmap fonts by outline fonts on most systems, thus reducing the problem to a mere mismatch between the label’s size and that of the manuscript’s text. In any case it is advisable to adjust the plot size from within Mathematica before rendering by applying IncludeGraphicsOptions to UnPSfrag, since rescaling at a later stage would also affect the labels.

It is also possible to follow a “pure” PSfrag approach, where all replacements are performed on the level of the manuscript. This is discussed in section I. Before, a number of usage examples shall be given.

V Examples

We start to consider in more detail figures LABEL:fig:poor and LABEL:fig:beautiful. The first one has been generated using standard Mathematica commands only, for the latter, the export was carried out with PSfragExport["example", exampleplot]//UnPSfrag.

Figure 5: Example plot without resorting to automatics; i.e., exported with PSfragManualExport. Additionally, the typesetting of the “” label has been manually improved.

In fig. 5 the introductory example fig. LABEL:fig:beautiful was reconstructed without resorting to the automatic positioning feature by using PSfrag and PSfragManualExport only. Additionally, one of the labels’ LaTeX code was improved to be instead of .

Fig. 6 demonstrates compatibility with the CustomTicks package Caprio:2005 , which can be used to customize tick marks, and the HoldForm command, which can be used to circumvent Mathematica’s automatic reordering of expressions into a normal form.

Figure 6: HoldForm example: Without HoldForm, Mathematica would normal order the label on the axis to . The CustomTicks package has been used to avoid the typical stripped decimal “1.” on the axis.

While early Linux versions of Mathematica do not reliably rotate text in an interactive session, PSfragExport has no problems in doing so, as has been shown in fig. 7. Note that for each piece of text, the PSRotation option is left unchanged (corresponding to “0”), thus preserving the original orientation of the PostScript text.

Finally, it has been demonstrated in fig. 4, that three dimensional graphics can be processed also, even though it has to be done manually with PSfrag commands, since the FullGraphics command, which is used to extract positioning information, only works on two dimensional graphics.

Figure 7: Example for substituting rotated text. To demonstrate that the new export function can preserve the orientation, only half of the labels have been substituted by LaTeX.

Vi Pdf

For publication of LaTeX documents, the author often not only has to provide the final manuscript but also the sources to produce them subject to constraints set by the publisher.

Therefore, MathPSfrag essentially offers two levels of image production, a rather sophisticated “UnPSfrag” approach, which aims at producing pre-rendered stand-alone images as has been described above, and a classical, PSfrag centric approach. In this approach, MathPSfrag is used to produce a tagged EPS file plus a PSfrag translation file, which can convert the tags back into readable labels during the LaTeX run of the manuscript. These two files are generated by PSfragExport. (Further use of UnPSfrag would join this pair into stand-alone graphics.)

The decision which approach to use has an impact on both the process of image creation and on how to include the images and compile the manuscript. In particular, the PSfrag centric approach is less convenient and not as compatible as the UnPSfrag approach, since it relies on PostScript. However it has the advantage of producing considerably smaller images of potentially better typesetting quality as the used fonts are guaranteed to match those of the document. Furthermore, the font size of labels is fixed in this approach, which is of particular importance for the bitmapped Computer Modern, though modern TeX distributions have outline fonts available, which scale more gracefully. Still visual consistency might suffer from differently scaled labels.

For inclusion of EPS images into pdfLaTeX manuscripts, a number of packages exist, mainly due to the widespread use of the equally PostScript dependent pstricks package. Here, only the pst-pdf package will be described, because it is compatible with beamer’s overlay techniques. An example presentation using \psfrag to change labels in a plot slide by slide is included in the distribution as well as examples for the other packages, ps4pdf and pdftricks, that could also be used to achieve pdfLaTeX compatibility.111I would like to thank Ross Moore for bringing these packages to my attention.

vi.1 Standard PSfrag (“PostScript only”)

The standard PSfrag way is to include the EPS and PSfrag file in a manner similar to the following code. The {psfrags} starts an empty group provided by PSfrag, whose sole purpose is making \psfrag definitions local to the following graphic.

The produced DVI file is then required to be converted to PostScript using dvips; and PDF can only be created by distilling from the PostScript version using for example Acrobat or Ghostscript(ps2pdf). Note that the popular dvipdf command(s) will not work.

The disadvantage of the pure PostScript approach is that the advanced typesetting features of pdfLaTeX are not available.

vi.2 pdfLaTeX (pst-pdf)

pst-pdf extracts all images of a manuscript in an additional LaTeX run with the help of the preview package.222A related package is auto-pst-pdf Robertson:2007 , which automatizes all of the following steps provided that pdfLaTeX can be called with the -shell-escape option. These can then be turned into a PostScript file and distilled to a PDF called image container. During the pdfLaTeX run, PDF replacements for PostScript parts are read from the image container. Whenever content or order of the images are changed in the manuscript, the image container must be regenerated.

The required steps are automated in a script accompanying pst-pdf. Unfortunately, the predecessor package ps4pdf, which is still installed on many systems, has a similar script sharing the same name, ps4pdf. It is important to ensure that the correct version of the ps4pdf script is used that refers to pst-pdf.

There is one additional catch due to the way \psfrag invalidates bounding boxes: pst-pdf must be loaded with the notightpage option and the ps4pdf script must be called with the --crop option.

Assuming manuscript.tex to be the main document, either of the following instructions produces the image container: [commandchars=
(),fontsize=] ps4pdf –crop manuscript.tex (or) latex manuscript.tex dvips -Ppdf -o manuscript ps2pdf -dAutoRotatePages=/None \() ()manuscript-crop.pdf pdfcrop manuscript-crop.pdf manuscript-pics.pdf Of course, a distiller different from ps2pdf may be used. Subsequently, the manuscript can be processed by pdfLaTeX in the usual manner, which will use the pre-generated pictures stored in the -pics.pdf file.

When uploading the manuscript to a preprint server that renames the main manuscript file, care has to be taken to explicitely specify the name of the image container as it will not be found by pst-pdf otherwise. This can be achieved as is illustrated in the following example. [fontsize=] Fcontainermanuscript-pics.pdf

The main advantage of this approach is that all images are collected in one single file, which can be very convenient for distribution, since it is much smaller than individual PDF versions of each image. This observation suggests that the collective image file is free of double copies of resources like fonts.

Vii Known bugs and limitations

MathPSfrag relies on three Mathematica commands: TeXForm, FullGraphics and AbsoluteOptions. All are potential sources of failure and their respective peculiarities are highly version dependent. A detailed analysis of potential traps is given in the manual. Here we shall concentrate on how to overcome certain restrictions or problems.

For versions 4.0–5.0 TeXForm produces Mathematica-specific LaTeX code that requires a compatibility layer or the style files and fonts provided by Wolfram Inc. This is explained in more detail in the appendix. Later Mathematica versions produce amsmath symbols and code, but the results will only be satisfactory for those Mathematica symbols that have a direct counterpart in LaTeX. For most applications this should of course suffice.

TeXForm generates a number format that corresponds to InputForm, while in plots TraditionalForm would be appropriate. It is strongly recommended to use the CustomTicks package whenever numbers on the axes are formatted unsatisfactorily. A simple TicksLinTicks provide as option to the Plot command suffices in most cases.

AbsoluteOptions is not always faithful in the sense that Show[myplot, AbsoluteOptions[myplot]] will not always generate the same plot. Most of the time, tick marks are affected. Again, this can be avoided by employing CustomTicks.

For three-dimensional plots, where manual alignment information has to be provided, the PSfragTicks command should be used for convenience.

If the LaTeX run performed by UnPSfrag fails, error logs are stored in internal variables and a help message will give hints of how to identify the error. Most of the time either a package is missing or a malformed LaTeX expression has been assigned to a label. The former can be solved by calling UnPSfrag with TeXPreamble"\\usepackage{missing}" and providing the missing package(s). The latter can be addressed by wrapping a PSfrag command about the offending Mathematica expression and assign better LaTeX code by hand using the TeXCommand option.

Since \psfrag-based images will in general have incorrect bounding boxes, MathPSfrag measures the bounding box by converting the image to a bitmap and counting non-empty lines. This should be more reliable than Ghostscript’s bbox device, which is known to sometimes produces incorrect bounding boxes. For speed and lower memory consumption, it is however possible to choose the bbox device by setting the UnPSfrag option BoundingBoxDevice{".bbox","bbox",""}.

In Mathematica version 4.1 under MacOS X (though other versions before 5.2 may be affected), displaying of bitmap images leads to a kernel freeze on subsequent usage of UnPSfrag. This can be avoided by setting PreviewDeviceNone to switch off generation of preview images.

Viii Conclusion

MathPSfrag provides a convenient interface to PSfrag permitting the generation of high-quality labels in Mathematica graphics. While it automatizes all tedious aspects of PSfrag, it still allows seamless overriding of all of its internal assumptions. The possibility to create images that do not depend on PSfrag anymore provides a simple method to achieve pdfLaTeX compatibility. For convenience, a preview feature has been introduced, which allows the user to easily ensure that the generated labels are both syntactically correct and yield the intended output.

Finally, MathPSfrag does not provide methods to construct correct tick mark contents as it is strictly focused on shape. As shown in fig. 6, it does however integrate well with the CustomTicks package Caprio:2005 , which provides that functionality.

For the future it would be interesting to incorporate the PSfragx extension that allows including the \psfrag commands into the comment section of the EPS file. It would be certainly desirable to export the position information, which is already extracted anyway, in the form of \overpic commands. In this context, the eps2pgf PW:2007 , which can convert EPS files in conjunction with PSfrag labels into pure TeX/PGF code, is also of great interest as it could be easily modified to produce such \overpic commands. This approach could allow circumvention of some of the bounding box related difficulties arising from the PSfrag approach and also achieve pdfLaTeX compatibility on a very fundamental level. Another possibility would be a package that renders all graphics into the correct size by calling LaTeX from within pdfLaTeX by means of the -shell-escape option.


I am grateful to Riccardo Apreda and Robert Eisenreich for helpful comments and discussion. Many thanks also to Will Robertson for extended testing and bug reports related to MathPSfrag under version 6 of Mathematica.

Program Summary

Manuscript Title: MathPSfrag: Creating publication-quality Labels for Mathematica® Plots
Authors: Johannes Große
Program Title: MathPSfrag
Journal Reference:
Catalogue identifier:
Program available from:
Licensing provisions: CPC non-profit use license
Programming language: Mathematica 6.0, 5.2, 5.0, 4.1
Computer: Tested on x86 architecture
Operating systems: Tested on Linux, Windows XP, MacOS X
RAM used during test run: 11 Mb
Keywords: Encapsulated PostScript, Mathematica, PSfrag, LaTeX
PACS: 01.30.Rr
Classification: 14 Graphics
External routines: CustomTicks package Caprio:2005 (recommended)
Nature of problem: Insufficient typesetting quality of labels in graphics exported from Mathematica
Solution method: An automatic export function is provided that generates LaTeX substitution labels.
Requirements: LaTeX, Ghostscript, PSfrag; recommended: ps2eps, Perl, pdfcrop, LaTeX package pst-pdf
Restrictions: The described method requires to some extent the use of Encapsulated PostScript (EPS) graphics though conversion to PDF is supported. Special Mathematica characters that do not have a direct counterpart in LaTeX will not show satisfactory typesetting quality. For Mathematica versions earlier than 5.1, the automatically created LaTeX code requires a compatibility LaTeX package, which is included in the package. In Mathematica 4.1, one of the examples does not work in its current form due to a bug in Mathematica’s Export command. However, the same effect can be achieved using exclusively MathPSfrag’s rotation mechanism. Moreover, in Mathematica 4.1 under MacOS X, display of preview images does not work.
Running time: 1 minute for all examples in this article

Appendix A Mathematica 4.x–5.0

MathPSfrag creates the LaTeX code that corresponds to a particular Mathematica expression by calling TeXForm. Starting from version 5.1 the TeXForm output is self-supporting code, which only requires a few standard packages, in particular amsmath. Pre-5.1 TeXForm output will require an additional style file providing Mathematica fonts that have to be configured accordingly WRI:tetex ; WRI:gsfont ; WRI:intoeps . In the new approach, since a large number of Mathematica symbols do not have counterparts in standard LaTeX packages, some symbols are created by gluing together existing symbols. When applied carefully, this method can achieve acceptable results though the current implementation is not optimal yet.

The problem with the pre-5.1 output in conjunction with the PSfrag method is that it requires the Mathematica fonts to be available in the publisher’s LaTeX installation, while in general they will—if at all—only be available to the author. (This should not be a problem when the author decides to follow the UnPSfrag approach, where all required fonts are embedded into the image files. It is then however necessary to include the style files by setting the according UnPSfrag option: TeXPreamble"\usepackage{...}".)

To avoid these problems in the PSfrag approach requires a compatibility package (mma4tex.tex) that is included in the MathPSfrag distribution. Basically it parses Mathematica 4.x–5.0 LaTeX code and replaces it by code similar to the output of version 5.1/5.2. When MathPSfrag detects Mathematica 5.0 or earlier, PSfragExport automatically creates PSfrag files that attempt to load mma4tex.tex and issue a warning when unsuccessful. There is also a corresponding style file mma4tex.sty that additionally loads the required font packages and ensures that mma4tex.tex is only loaded once. It is recommended to include it in the preamble. Therefore both files have to be installed where LaTeX can find them; e.g., in a directory tex/latex/mma4tex/ relative to the texmf directory of the LaTeX distribution. Thereafter the file database (“ls-R”) has to be updated. Again the details depend on the distribution. Typical names of the update command are mktexlsr or texhash. For MiKTeX there is the choice between the command line program (initexmf -u) and a graphical configuration program (“MiKTeX Options” or “Settings”; press the button “General/File Name Database/Refresh Now”).