Preparing ('publication quality') figures and Matlab graphs

18 downloads 199 Views 427KB Size Report
2 Apr 2007 ... able to find to integrate Matlab with LATEX to create figures that ... In Matlab, the laprint package is used to create eps and .tex files that run ...
school of mechanical engineering technical memorandum 002

Preparing (‘publication quality’) figures and Matlab graphs

Will Robertson AVC Group School of Mechanical Engineering The University of Adelaide∗ Reviewed by: Dick Petersen

April 2, 2007

1

Introduction

Graphs and plots are a natural way to visualise data. It hardly needs saying that their use is common even in non-technical documents. Unfortunately, much work is often required (and rarely performed) to produce plots with sufficient output quality to match a well-typeset document. This article covers the easiest solution I have been able to find to integrate Matlab with LATEX to create figures that match the quality of the document itself. Those who aren’t using LATEX (or similar) in the first place probably aren’t interested in good typesetting, and won’t find much of interest within.

2

Technical overview

This article is structured as a tutorial; for those who know a little about what’s going on, here’s an overview of the techniques demonstrated. • In Matlab, the laprint package is used to create eps and .tex files that run through the LATEX package psfrag package to obtain the output desired. • For users of LATEX who create dvi output, which is converted to pdf via the toolchain dvi→ps→pdf, this is all that is required. • For users of LATEX who use the pdfTEX engine to output pdf directly (this is common on the Mac, for example), more steps are required, using the pst-pdf LATEX package and the pdfcrop Perl utility. This is automated with a package of the author. ∗ Copyright

© Will Robertson & The University of Adelaide Not to be modified or distributed without consent of the author.

1

A small section is devoted to creating other sorts of graphics using these same methods, (namely, psfrag) in order to be able to use the documents fonts, with maths, in diagrams and other included graphics.

3

The problem

Complex mathematical tools exist for creating and analysing data, and graphs are often used to visualise the results. However, the abilities of Matlab to create graphs is generally rather poor with respect to typesetting and font selection. While passable figures can be produced when one learns the intricacies required, many people do not spend the time to do so. This article will not discuss the finer points of data representation; the author is neither an expert here nor are the tools discussed relevant to this task. In this article, Matlab is used to generate graphs, which will be post-processed as they are being inserted into a LATEX document. This method is the best trade-off, in the author’s opinion, between ease of figure creation and typesetting quality. Better results could be achieved by using an external program to process the data produced by the analysis software, but doing so would be much more tedious. To start with an example, consider the Matlab commands peaks; print -depsc2 peaks

This produces a 3d plot similar to the Matlab logo. The eps file created (with default options) is shown in figure 1.

First problem In order to fit it into the document, it had to be shrunk considerably. Consider now the axis labels — they have also been shrunk, and subsequently have become much too small. The naïve solution to this problem is to increase the font size used. A better solution, more rarely employed, is to decrease the width of the figure saved out of Matlab.

Second problem Using the same fonts in figure labels as in the main document is desirable for reasons of consistency and aethetics. While it is sometimes possible to match (or more usually, to approximate) the document font from within the data analysis program when the figure is saved, this isn’t ideal because the document fonts themselves might not be constant,1 and the maths quality will never equal that of which LATEX is capable. 1. For example, Times Roman in a paper, Palatino in a thesis, Charter in a presentation.

2

Peaks

8 6 4 2 0 −2 −4 −6 3 2

3

1

2 0

1 0

−1

−1

−2 y

−3

−2 −3

x

Figure 1: A figure created by Matlab, using its default parameters. It has been shrunk to the width of the text of the document. Even at this large size, the fonts used for labelling are too small.

3

4

The solution

Using the correct tools, creating decent figures can be easily automated. The steps involved are: 1. In Matlab, create the figure, and set the font sizes, 2. and save the figure with the desired width; 3. then input the figure into the LATEX document.

4.1

Font sizes

The first stage of the solution comes from within Matlab itself. When figures are created, they should be saved with the font sizes desired in the output. The process of saving the figure will involve resizing it to the desired width. To change the font size of the axis labels and title in a Matlab figure to 11 pt and the font size of the tick labels to 9 pt, use the following function. figfontsizes(11,9);

Further work needs to be done to change the legend label font sizes separately. (Contributions welcome; this was put together rather hastily.)

4.2

Saving the figure

This is the easy part; the laprint package does everything you need.2 This package has a large number of options, almost all of which are unnecessary to adjust for the purposes of this article. Following is an example of its use to create the figure peaks-nice.eps, 9 cm wide. laprint(gcf,'peaks-nice','width',9,... 'asonscreen','off','keepfontprops','on',... 'factor',1,'scalefonts','off','mathticklabels','on')

The last three options should probably always be set. 'asonscreen' for some purposes might be better switched on. 'keepfontprops' allows the fonts in the figure to scale with the fonts in the document, but also makes every string in the figure the same font size. It is left as an exercise to wrap this code into an easier-to-use function. The code above produces the output shown in figure 2. Note that now the figure does not require scaling to be inserted into the document, and the axis labels use the same font as the document. Even better effects can be achieved by inserting LATEX strings into the Matlab figure. For example, the following code will create the graph shown in figure 3. t = linspace(1,7,1000); omega = 10; 2. The Mathematica package MathPSfrag performs the same job in that program.

4

Peaks

5 0

−5 2

2

0

0

−2

−2

y

x

Figure 2: A figure created by the laprint package in Matlab. The figure is inserted at actual size.

F = exp(-t).*cos(omega*t); figure; plot(t,F) xlabel('Time, $t$') ylabel('Force, $F$') title('Graph of $F=e^{-t}\cos(\omega t)$')

That is, pure LATEX can be included in the figure and it will be correctly rendered in the document. This method also allows abbreviations defined in the document in the figure labels themselves, for added convenience and consistency.

4.3

Using the figures in LATEX

The previous section covered creating the figure in Matlab and saving it with the laprint package. Now, the figures must be included in the LATEX document. I have written a simple package, auto-pst-pdf, to simplify this process, which is also attached within this pdf. Include it in the preamble of the document: \usepackage[on]{auto-pst-pdf}

This package is designed to be used for document compilation under either LATEX or pdfLATEX and the output will (should) be equivalent. This is useful for testing the document while compiling to dvi (which can be faster), while still ensuring that pdfLATEX can be used for the final document (for advanced features such as font expansion with the microtype package, pdf file attachments with the attachfile package, annotations, etc.). 5

Graph of F = e−t cos(ωt) 0.3 0.2

Force, F

0.1 0

−0.1 −0.2 −0.3 −0.4

1

2

3

4

5

6

7

Time, t Figure 3: Plotting a damped sinusoid, F = e−t cos(ωt). Note that the fonts used in the figure exactly match the document. Include the figure in almost the same way as usual; instead of the command \includegraphics, use \matlabfig instead: (see figure 2) \begin{figure} \centering \matlabfig{peaks-nice} \caption{A figure created by the \pkg{laprint} package...} \label{fig:peaks-nice} \end{figure}

‘Regular’ LATEX documents

For LATEX users who produce dvi files, that’s all there is.

pdf TEX documents More effort is required for LATEX documents compiled with the pdfTEX engine, because the eps translation that occurs in the conversion from dvi to pdf cannot take place (it is during that step that the magic occurs). The solution is to use the pst-pdf package, which compiles the images in a separate process before including them in the final pdfLATEX document. Luckily, the auto-pst-pdf package takes care of these details automatically. It requires that pdfTEX be invoked with the --shell-escape option in order to run external programs,3 and that the pdfcrop Perl script is installed. Under the MiKTEX 3. Enabling this feature may well be the most complicated part of the process. Ask someone who knows such things how to do it.

6

distribution, although the script itself is already installed, this requires a Perl installation.4 Once the figures are finalised, compilation time can be halved by adding the [off] package option to auto-pst-pdf: \usepackage[off]{auto-pst-pdf}

5

Other diagrams

In the previous sections, a method was shown to obtain nice looking graphs from Matlab using fonts from the LATEX document. This is a harder problem than inserting plain old diagrams and other such graphics with nice maths and matching fonts. To perform this task, the psfrag package is used directly (this is the package that enables the usage encapsulated by auto-pst-pdf so far). This involves placing unique strings in the eps file and writing a LATEX equivalent substitution for when the graphic is included in the document. (See the psfrag documentation for more information.) An example is shown in figures 4 and 5, which show the original and processed graphic, respectively.5 If the graphic is called example.eps, then the mapping from graphic strings to LATEX labels can be placed in the file example-psfrag.tex: \psfrag{[Mp]}{$M_p$}% \psfrag{[hb]}{$\mathbf h$}% \psfrag{[epb]}{$\mathbf{e}_p(n)$}% \psfrag{[evh]}[r][r]{$\hat{e}_v(n)$}% \psfrag{[epsv]}{$\varepsilon_v(n)$}% \psfrag{[ev]}{$e_v(n)$}%

Alternatively, for substitution labels that apply to every psfrag-formatted figure, they can be placed in the file -psfrag.tex. The graphic is then inserted with the \psfragfig command: \begin{figure} \centering \psfragfig{example} \caption{An example of the \texttt{\string\psfragfig} macro.} \label{fig:ps2} \end{figure}

6

Summary

With some simple packages, it becomes easy to automatically create high-quality graphics that match the look of a LATEX document. The following items must be installed to follow this article: 4. Free download: http://www.activestate.com/store/activeperl/download/ 5. Thanks to Dick Petersen for the example.

7

ev ( n )

[ev] [epb]

[evh] _ [hb]

+

e p (n)

[epsv]

S

h

eˆv (n) _

+

ε v (n)

S

Mp

[Mp] Figure 4: Raw eps graphic to be processed by psfrag.

Figure 5: An example of the \psfragfig macro.

• The Matlab package laprint; the function figfontizes makes things easier (contained inside this pdf file). • The Perl script pdfcrop; this needs a Perl installation under Windows. • The LATEX packages psfrag, pst-pdf; the package auto-pst-pdf (embedded within this pdf file) automates the steps required to run these packages and provides a convenient interface to insert figures.

7

Epilogue

Dark green links in this document correspond to hyperlinks to external packages and software. pdf attachments are indicated by grey icons in the margins of the document, which may be extracted using Adobe Reader or pdftk. The LATEX source of the current document is attached. It uses many of the macros discussed in the article itself. The attached Matlab script examplelaprint.m generates the figures in this document.

8

Suggest Documents