Jens Nöckel's Homepage

Computer notes home

Creating and Post-Processing Mathematica Graphics on Mac OS X

Table of contents

Mathematica runs on many platforms, including Mac OS X. This page is written from a Mac OS X perspective, but if you're on a different platform you may still get some useful information here. In the past, I've also heavily used Mathematica on UNIX and Windows systems, and you shouldn't have any trouble adapting what I'm writing here to those other platforms. However, I have to leave that as an exercise for the reader.

Of course, if you need real expert help, you could always check the mailing list.

To obtain Mathematica through the University of Oregon site license, go to public.uoregon.edu.

  1. Should I be using Mathematica version 6 or version 5?

    After some intensive use, we have decided that Mathematica 6 is currently still unstable. Crashes with data loss have happened even after updating to 6.03, in unexpectedly simple situations where I don't want to waste my time investigating the cause. So if you use version 6, save your notebooks frequently under different file names.

    There is an autosave feature (which is disabled by default) but it doesn't keep versioned backup copies. If you use it, set up frequent backups in some other way, e.g. using Time Machine on a Leopard Mac. If you've used Mathematica for a few years, you'll not be too surprised when the program "unexpectedly quits" during some grueling calculation. But when a program loses all your changes just because you follow a "More Info" link to the Documentation Center, then I would call that truly unexpected. Your productivity with Mathematica 6 will be greatly increased if you expect the unexpected.

    Here are some facts to weigh when thinking about version 6:

    • If you're new to Mathematica, it would seem wise to start with version 6. However, the most important thing for a beginner is good documentation, and that's not easy to find for the new version. You'll have a lot of fun with Mathematica 6 if you like doing your own detective work:
      • There is "Virtual Book" similar to the old Mathematica book built into the help system of version 6.03. This should be the place to start.
      • A good place to look for ideas is the Wolfram Demonstrations Project.
    • The new features are nice for in-class demonstrations because a Mathematica notebook exposes the "guts" of functional evaluations while at the same time allowing interactive manipulation of the results.
    • On the other hand, for larger projects you don't really need interactive features, especially when they become unrealistically slow with large data sets.
    • With too much interactivity in a notebook, the Frontend starts feeling like a web page crowded with badly coded Java applets. After playing with this for a while, I much prefer my notebooks to be source-code oriented rather than GUI oriented.
    • Almost every half-way complex computation requires learning new or modified Mathematica syntax if you are switching from version 5.
    • Writing notebooks in Mathematica version 6, you lose backward compatibility, which may be a problem especially if your notebooks are intended for an audience who can't afford to upgrade from an earlier version yet.

    Bearing all this in mind, below are some things you may want to know when using Mathematica version 6. If you decide to stick with version 5, jump to the bottom of this page for hints that apply to all versions.

  2. Avoiding Mathematica Version 6 graphics incompatibilities:

    If you have old Mathematica notebooks (from version 5.2 or below) containing fancy graphics, then converting them to Mathematica Version 6 can be a lot of work. To avoid this, I put the following at the beginning of such notebooks:
    If[$VersionNumber >= 6., <<Version5`Graphics`,  <<Graphics`Graphics`; <<Graphics`Graphics3D`]
    Doing this (or some variation on the above), old notebooks become useable, in particular 3D graphics and animation where the transition to Version 6 has brought deep changes. See the list of incompatible changes at Wolfram.com.

    The If[$VersionNumber >= 6.,...] statement above is intended to make the notebook work in all versions of Mathematica, but this may need tweaking depending on your content (in particular the add-on packages you're calling). Most importantly, the notebook has to be authored and saved in version 5.x, because V 6 doesn't have an option to save in "V 5" - backward compatible format, and trying to load a V 6 notebook into Mathematica V 5 typically results in a crash!

    By loading <<Version5`Graphics`, you give up the main new features of version 6 graphics. But more importantly, there appears to be no direct way to save the resulting graphics as external files (EPS, PDF, PNG, etc.). You'll have a working notebook, but version 6 will silently refuse to Export pictures from it (low-level functions like Display don't seem to work either), leaving you with only two options:

    1. Take a screen shot. This of course creates a resolution-dependent bitmap.
    2. Open an empty notebook, and copy the desired graphics output into it. Do this by selecting the cell bracket for the graphic, not via the contextual menu of the image. Once the plot has been pasted into the new notebook, print it to a PDF file. This creates a file you can use in an external graphics application, but it is also rasterized.

    Switching back from V 5 to V 6 graphics is done by entering <<Version6`Graphics`. Unfortunately, after this switch, the graphics you produced with the old graphics commands are likely to produce errors whenever you try to process them further (e.g., copying a V 5 graphics cell doesn't work).

    Below I address some specific compatibility issues as I encounter them.

    • Plot labels with complex formatting

      Shown below is a simple plot, executed first in Mathematica V. 5 (left) and then in V. 6 (right)

      In the Notebook, I used the symbol γ as a variable, but also as a frame label. In the label, I use "γ" in quotation marks to avoid getting the evaluated value of the variable γ as the horizontal label. Similarly, I quoted the symbol for the vertical label. So far, so good. But in version 6, the same method doesn't give the expected results, even though I've activated Version5`Graphics`. Not only do the quotation marks appear in the frame labels, but moreover the expression fγ is not displayed as it should be. Everything works fine if I use Mathematica V. 6 without Version5`Graphics`.

      How can the frame labels be written in such a way that they display properly in both version 5, and version 6 with (or without) Version5`Graphics`? The solution is to use the following plot command instead:
      Plot[Sin[γ], {γ, 0, π}, Frame -> True, FrameLabel -> {HoldForm[γ], HoldForm[fγ]}]
      If we want our labels to be compatible with old and new versions of Mathematica, this is the way to do it.

    • 3D plotting functions

      In Mathematica version 6.0.3, some 3D plotting functions from the legacy add-on package Graphics3D have not yet been incorporated into the System context. For example, this applies to

      • Shadow
      • ShadowPlot3D
      • StackGraphics
      • ...
      The <<Version5`Graphics` trick won't bring them back, either. To accesss these functions, we have to load the Graphics3D add-on package in V 6. If you plan on using none of the new graphics features of V 6, you could just do the following:
      If[$VersionNumber >= 6., <<Version5`Graphics`,  <<Graphics`Graphics`];
       <<Graphics`Graphics3D`

      Although this produces more warnings, it gets those shadow plots working properly.

      On the other hand, if you follow this route, you won't be able to run the command shown in the picture on the right. It uses a new V 6 feature, the Tube directive. In earlier versions of Mathematica, the command ParametricPlot3D creates one-dimensional lines that make it difficult to visualize complex 3D curves such as knots. Mathematica Version 6 now lets you choose a tube of user-specified diameter to represent the curve. The example plot uses the code
      Shadow[
      ParametricPlot3D[{3 Sin[4 π t], 4 Cos[4 π t], Sin[2 π t]}, {t, 0, 1}, PlotStyle -> {Tube[0.1]}]
      ]

      You'll get an error here, unless we abandon the  <<Version5`Graphics`. I.e., you should only include the line
       <<Graphics`Graphics3D`
      This combines the best of the V 5 and V 6 worlds, in that the resulting curve is tubular with projections, and can even be interactively rotated.


  3. Picking coordinates out of a plot using the mouse

    In 2D plots, it isn't always easy to accurately read off data by eye. In all earlier versions of Mathematica, you can examine the numerical values corresponding to positions in your plot by highlighting the graphic, then pressing Command. The current mouse position then appears at the bottom left of the Notebook window. You can click the mouse to make marks, and even copy marked coordinates by pressing Command-C.

    In Mathematica 6, this no longer works. Instead, this functionality can be produced using dynamic interactivity. In particular, enter the following anywhere in the Notebook:
    Dynamic[MousePosition["Graphics"]]
    and the result is a continuously updated mouse position, whenever you hover over a plot. The coordinates here are those of the graph's PlotRange. If the option "Graphics" is omitted, the coordinates are referenced to the Notebook window.

    I noticed that this dynamic function gives wrong coordinates in the MatrixPlot output (one coordinate axis is inverted). If you want the correct output with MousePosition, use ListDensityPlot instead.

    You can even get almost the old behavior back by drawing your graphics using the StatusArea command, as shown in this example from the documentation:
    Dynamic[StatusArea[Plot[Sin[x], {x, 0, 10}], MousePosition["Graphics"]]]
    Of course, this may eventually only have sentimental value since the coordinates in the status area are actually harder to read than a normal Notebook line.

    Arguably a more useful operation is to actually copy and save the mouse coordinates at selected points in the plot. To get a snapshot of the mouse coordinates in the graph every time the mouse is clicked, enclose all plotting commands in a ClickPane directive, e.g.,
    ClickPane[ Plot[Cos[x], {x, -π, π}, Frame -> True, FrameLabel -> {α, "cos α"}], (pt = #) &]
    which will update the variable pt at every mouse click in the plot. Now you have to dynamically display this variable somewhere in the Notebook:
    Dynamic[pt]
    That captures the desired coordinates.

    If you don't want to re-evaluate the expression that draws your plot, just to make it clickable, there is a more indirect way:

    1. Copy the plot
    2. Type ClickPane[
    3. Paste the graphic image at the cursor position
    4. Finish by typing , (pt = #) &]. This is what it might look like:
    5. The new cell contains a copy of the image which is now clickable, and the coordinates can be read off using
      Dynamic[pt]
    All in all, this particular task was easier in previous Mathematica versions, but the new way of doing things is very systematic and relatively easy to get used to.
  4. Pitfalls of mouse interactivity

    With new features come new pitfalls, too, and Mathematica's new interactivity is no exception. You will notice this when you try my above Clickpane[] suggestion with a reasonably large plot, containing so many data points that it takes a perceptible time to draw. The mouse clicks will then be registered with an annoying time delay. This is, I think, a real stumbling block in data-intensive applications. To boil this issue down to its core, I've tried the following simple experiment: Copy the following code into a Mathematica Input line and press Shift-Return:

    x = Dynamic[MousePosition[]]
    
    {ListPlot[
      Evaluate[
       Table[{.5, 0} + Exp[-t/100] {0.5 Cos[t], 0.5 Sin[t]}, {t, 0, 100, .001}]],
      Frame -> True], x}
    

    This may take a second or two to generate the graph of a dense spiral. The main thing to observe here is the displayed mouse position: Its coordinates are updated very sluggishly, both in the Out[] line of the assignment x = , and in the Out[] line containing the graphics object together with the value of x in a list.

    Now edit the above input so that the graphics object does not appear combined with the current mouse position, by changing the x at the very end to "x". Note that the Mouse position displayed as the first output line is now much more responsive.

    There is absolutely no difference between the graphics objects I am defining in either case, but the mere fact that the dynamic variable shares the same output cell as the graphics object in the first example causes a dramatic slow-down of the user interface. The delay doesn't seem to be caused directly by a redundant redrawing of the graphics object, but the Front End event handling is clearly inefficient. I'm currently waiting to hear back from Wolfram's experts on this; stay tuned.

  5. Exporting graphics with opacity effects

    Mathematica V. 6 has introduced the ability to create opacity effects, both in 2D and in 3D graphics. Transparent portions can be useful in Mathematica graphics because they let you display several objects without having them obscure each other. A simple example in 2D plots are intesecting areas such as those created by the Filling option. In 3D, surfaces with opacity less than one let us reveal axes and other objects that might otherwise be obscured.

    That's all very well as long as you're content with Mathematica itself as the vehicle for disseminating your work. But normally this isn't where you'd want to stop. You'd go on to export your graphics for inclusion in some other media, e.g. PDF or HTML, or for post-processing in a graphics program.

    What happens to transparency then?

    For the most part, what you really want is for the graphic to look the same in the external application as in your Mathematica Notebook. That means, once opacity has done its job of revealing various hidden things in your Mathematica plots, there is no need for the exported graphic to "remember" that it came from a partly transparent object. In that case you'll be fine choosing any export format that's convenient, making sure to think twice about using vector formats when exporting 3D graphics (because the files can get huge).

    Things get a bit more difficult if you insist on maintaining transparency as a property of the exported graphics. There are not too many formats that support this.

    • The most well-known bitmap format that does this is GIF, but one can also use PNG or TIFF instead. Not among the eligible formats is the popular JPEG. In Mathematica, GIF is the most flexible choice, because it supports the option TransparentColor. Here is the syntax:

      Export["plot.gif", Style[%, Magnification -> 2], "TransparentColor" -> White]

      If you want to get a transparent PNG or TIFF, replace the option "TransparentColor" -> White above by Background->None. Alternatively, if transparency is desired for other parts of the image, you could first use the command Export["plot.png", Style[%, Magnification -> 2]] (version-6 syntax), and then process the result along the lines of the notes on transparency in bitmap graphics. The option Magnification -> 2 magnifies graphics including plot labels, whereas an option such as ImageSize -> 600 makes the plot labels look smaller compared to the graphics.

    • As for vector formats, the good old EPS format is out when transparency is desired. But you can export as PDF or as SVG. Since PDF is the most familiar one, that may be preferred by many. If you open such a PDF in Illustrator, it will retain the opacity settings from Mathematica. You don't see that at first, though, because the PDF is by default exported with a solid background. To get the transparent appearance back, export your plot as follows:
      Export["plot.pdf", Style[%, Background -> None]] (V 6 syntax).
      For completeness: you can remove the background in version 5 PDFs, too, by typing Export["plot.pdf", %, ConversionOptions -> {"Background" -> None}]]

      The picture on the right shows a Mathematica-generated PDF, with a black gradient added in Illustrator to show that the sphere is translucent.

      If you choose SVG export, then the default is to include no background, so there's no additional step involved. The disadvantage of SVG is mainly the lack of full support for its specification in many graphics editors and browsers. Adobe Illustrator does a good job with SVG, but for complex SVG graphics I would recommend Inkscape, which is free but very capable, with SVG as its native file format. The newest version of Inkscape can also read PDF files. In my experience, Inkscape was able to handle even SVG files that Illustrator choked on.


  6. Exporting movies
    • Quicktime

      Quicktime (.mov or .qt) is a popular movie format, especially on Mac platforms. This format was never available directly in the Export command, but in V 5 it's easy to produce via the Frontend menu item Edit → Save Selection As.... As the name implies, one selects a sequence of graphics cells and gets the Quicktime movie. One additional step is required in the Compression Settings dialog: Shift-Option-Click on the preview to make it fit into the pre-defined movie bounding box (however, this never worked reliably).

      In Mathematica V 6, exporting Quicktime has become slightly more complicated, but the results are better. First of all, the Export command still doesn't know about Quicktime, whereas Import does. Let's assume you've produced a Table of graphics along the lines of
      a = Table[ Plot[Sin[ω t], {t, 0, 10}, PlotRange -> {-1, 1}], {ω, .1, 2, .1}]
      Then you'll be disappointed to find that selecting the output and going to the Quicktime export window via File → Save Selection As..., Mathematica only lets you make a single picture of all frames combined. To get the old behavior back, we first have to unravel the list in which the graphics is wrapped. After making the list as described, add the following line:
      Map[Print, a]
      This will create all the plots conveniently bracketed in a CellGroup which you can select with a single click. With this, Quicktime export can proceed as desired. The bounding box of the movie seems to be correctly set, even without the manual Shift-Option-Click adjustment mentioned above for V 5. In order to avoid color artefacts, choose a large value for the color depth (this helped me fix an issue with unexpected black areas appearing in ListPlot-generated frames).

    • Flash

      Flash .swf export is a new feature of Mathematica V 6. This is probably the most efficient export format for typical Mathematica-generated graphics, in terms of file size (as I also discuss in the context of web movies), and quality. To make a Flash movie from your list of plots, the usual syntax Export["a.swf", a] will do the job.

  7. Annotating graphics within Mathematica

    One of the new features in the Mathematica 6 user interface is the ability to do interactive drawing and typing directly in a plot. For example, to add an arrow with some explanation to a plot, just highlight the graphic, press the "a" key and drag the mouse to get an arrow. Then press "t" to get a text field. You can enter both text and equations here.

    This annotated picture can be copied as PDF (I found I have to select the bar on the right of the graphic first), and pasted into other applications (e.g., Preview). Likewise, the selected picture can be saved to a PDF file via Edit → Save Selection As.... With that added drawing capability, Mathematica makes it much easier to create plots that don't require post-processing in other applications such as Adobe Illustrator. You can now go from Mathematica to your LaTeX document, or another document preparation system, without detour.

  8. Editing graphics within Mathematica

    When it comes to manipulating graphics, one should distinguish between annotations (adding content to the picture), and edits (in the sense of actually modifying the pictorial content). In Mathematica, you can do both. In the screenshot to the right, the spikes are not a malfunction, they were edited in by hand. What you do to edit a plot like this, is to double-click on the graphic, then double-click on the curve. This makes the individual points of the curve editable. The mouse can now be used to drag them around. I haven't figured out how to select the axis labels and edit them, though. Obviously, in the context of this page, that would be the more useful application of Mathematica's new editing capabilities.


  9. Mathematica graphics shows incorrect fonts in Adobe Illustrator

    However, Mathematica's interactive drawing tools are only a meager subset of what a program like Adobe Illustrator can do, and so the interoperability between these two programs remains an important issue. Unfortunately, the more of your annotation you do in Mathematica, the more likely you are to encounter the peculiarities discussed next: Getting Illustrator to read Mathematica fonts is a tricky business because it depends on your configuration. In particular, it depends on the Mathematica and Illustrator versions. I'll assume Illustrator CS 3 and Mathematica Version 6 here. If you're interested in older versions, check the web archive.

    Let's start with a plot made and annotated in Mathematica. Screenshot of a Mathematica Graph

    How do you get this into Illustrator? Here are my own three solutions to the Mathematica font problem.

    1. Export as EPS with advanced options
    2. Copy and paste from the Notebook
    3. Use a custom export function
    4. Save as TeX: no longer an option since Mathematica 6 can't directly export graphics to LaTeX! You have to convert your graphics cells to Postscript first (via Cell > Convert to...).
    Now for the details.
    1. Export as EPS with advanced options:

      Exporting from Mathematica to Illustrator works flawlessly if you make sure not to include special fonts in the exported file by setting the corresponding option as described below. To reiterate this point: you can use all the special fonts in your plot, but do not embed them in the exported EPS file so that Illustrator can instead look them up on its own among the Mathematica (and other) fonts it has available.

      • My starting point is that I can select and use all of the Mathematica Fonts from the Illustrator Type/Font Menu. Try this - if you can type greek letters after choosing Mathematica 1 Regular, then we're on the same page. If you do not have these fonts available in Illustrator, then you can get them from Wolfram's web site.
      • In Mathematica, generate any kind of graphics you wish, then export it as an EPS file using the following option (see the screenshot above):
        Export["test.eps",%, "EmbeddedFonts" -> False]). This syntax is for Version 6. In earlier versions, you would replace the option by ConversionOptions -> {"IncludeSpecialFonts" -> False}.
      • Now the EPS file without included fonts can be opened by Adobe Illustrator (either from the file menu or by dragging the file onto the Illustrator icon, or any way you like), and the Mathematica fonts should all be there, including Greek letters etc. This will work provided that all the fonts you are using in the Mathematica output are also available in Illustrator. One shortcoming is that the EPS file format doesn't preserve transparency, so you lose effects created with Opacity and related Mathematica functions. Unfortunately, other file formats such as PDF don't support the "EmbeddedFonts" option.
      An example plot in Mathematica:The result in Illustrator (from an earlier version):

      This is a random item from my thermodynamics lecture, and the formula in the plot uses various different fonts, including FontFamily → "Helvetica Neue" for the Latin text. Bold Italic and simply Bold weights appear (by accident, but it's good as an example). The formula is actually rendered better in Illustrator.

    2. Copy and paste from the Notebook:

      If you produce a plot in Mathematica (assume Version 6) and highlight the output graphics object, right-clicking brings up a contextual menu which allows you to copy as PDF or as PICT. You may be able to get good results with PICT because it can in principle preserve vector information. However, when I tried it with the plot shown at the top of this page, the text looked wrong, as if the font outlines were drawn with incorrect handedness (thus confusing inside and outside).

      With the PDF version of your plot on the Clipboard, there is no problem getting a faithful copy into the Preview Application by choosing New from Clipboard. However, pasting into Illustrator won't preserve the appearance of the fonts.

      One rather useful application for the PDF copy-and-paste method is for people who typeset formulas in Mathematica instead of using LaTeX. I have used Mathematica's typesetting capabilities in this way, too. In order to type a formula in Mathematica, one usually is in text mode: start a new line and press Command-7, then start a formula with CTRL-(. When the math expression is completed, selecect the text cell (i.e., the vertical bar to the right of it), and copy it as PDF. If you prefer Mathematica to LaTeX, this is an alternative to tools like LaTeX Equation Editor, Equation Service or LaTeXiT in particular for use with the Keynote Application.

    3. Use a custom export function

      There are other programs that can convert EPS to PDF or other formats, and one can go through such a third program before importing into Illustrator. In particular, you can use ghostscript to strip away all fonts that cause trouble when importing into Illustrator. Define the following Mathematica function:

      epsExportNoFonts[exportName_, ob_] := Module[{},
          Export[exportName, ob, "EPS"];
          Run["gs -sDEVICE=epswrite -dNOCACHE -sOutputFile=nofont-" <> 
              exportName <> " -q -dbatch -dNOPAUSE "  <> exportName <> " -c quit"]]
      

      Then use this function instead of the built-in Export[] to write your Mathematica plot as an eps file: epsExportNoFonts["myfile.eps", graphics]. This function writes two EPS files: one called myfile.eps and a second one called nofont-myfile.eps. The file with nofont- prepended can be imported into Illustrator and should cause no font substitution problems. If Mathematica returns with a "0", there was no error. If the return code is something else, it may be because gs is not found. This could mean that you don't have ghostscript installed, or that you need to provide the path information, by replacing, in the above code, Run["gs... with Run["/sw/bin/gs (or whatever the path is that you get from which gs in the Terminal). On my system, this is not necessary because I have a file .MacOSX/environment.plist through which this path information is provided to applications such as Mathematica.

      As with any EPS Export from Mathematica, the shortcoming is that transparency isn't preserved (something that hasn't concerned me until now, since earlier versions of Mathematica didn't have it anyway).


noeckel@uoregon.edu
Last modified: Fri Jul 25 23:34:10 PDT 2008