# 玉琪的学习备忘录

## Improve MATLAB Figures for Publication

(2010-03-25 15:56:33)

### 教育

In this post I will be showing how to produce a publication quality figure using MATLAB (2007a). To fully appreciate the content presented here you will need some working knowledge of MATLAB, meaning that you should know how to create a basic plot. If you need some help in this department you can reference this Guide from MathWorks. But, if you’re ready to create a publication quality figure (i.e., one that doesn’t look like it was made in Excel), then keep reading.

Suppose I am raising two different species of fruit flies in my lab, and once a day for 10 days I measure the size of both populations and record the numbers in two vectors called Species1 and Species2. Now I want to visually compare the growth of the two populations over the 10 days so I use the following basic plotting commands

h1 = plot( Days, Species1 );
hold on;
h2 = plot( Days, Species2 );

*Note that the vector ‘Days’ contains the numbers 1 through 10 which represents the days over which the experiment took place.

### Step 1: Change the background from gray to white

The gray border that I’ll call the “background” of the Figure 1 is not desirable for publication, so this gray can be changed to white with the two relatively simple lines of code shown below. I have appended each line with a comment (denoted by the percent % symbol standard in MATLAB.)

fh = figure(1); % returns the handle to the figure object

set(fh, ‘color’, ‘white’); % sets the color to white

As you can see, Figure 1 is now one step closer to being ready for publication. Notice the `set` command in the lines of code shown above, which can be implemented in general by using the following syntax

set(H, ‘PropertyName’, PropertyValue, …);

### Step 2: Cutomize Line Styles

There are still some serious problems with Figure 1, namely the fact that both data sets are currently represented by solid thin blue lines. We’ll want make changes so that the individual data points (corresponding to each species) are shown in addition to lines connecting the points. For the first data set that corresponds to Species 1 I want to use gray circles connected by a solid black line. Species 2 will be shown as white squares connected by a dashed black line. Note that in both cases I plot the lines first, followed by the markers (circles or squares):

set(h1, ‘LineStyle’, ‘-’, ‘LineWidth’, 1.0, ‘Color’, ‘Black’);
set(h1, ‘Marker’, ‘o’, ‘MarkerFaceColor’, [0.5 0.5 0.5], ‘MarkerEdgeColor’, [0 0 0], ‘MarkerSize’, 8.0);
set(h2, ‘LineStyle’, ‘–’, ‘LineWidth’, 1.0, ‘Color’,’ Black’);
set(h2, ‘Marker’, ’s’, ‘MarkerFaceColor’, [1 1 1], ‘MarkerEdgeColor’, [0 0 0], ‘MarkerSize’, 8.0);

Notice that I’ve used the `set` command again to define the characteristics of the different properties I wanted to change. To get a full list of the property names it is nice to bring up the ‘Property Inspector’ panel associated with the MATLAB figure. In the menu bar of the Figure window click ‘View-Property Editor’.

Once the property editor appears, highlight the aspect of the plot you wish to alter (e.g., the curve corresponding to Species 1 or the x- or y-axis), then click the ‘More Properties’ button to reveal the Inspector. This Property Inspector feature provides a long list of different property names and the values associated with whatever feature of the graph is highlighted. Notice that so far I have only altered properties associated with the data, so now I’ll move on to some more changes.

### Step 3: Alter the axes

One of my pet peeves with MATLAB’s figure making capabilities is the way the axes look by default. I’ll want to remove the ‘box’ so that only the standard x- and y-axes are shown.

set(gca, ‘Box’, ‘off’ ); % here gca means get current axis

Conveniently the default axis limits are such that I don’t need to change them. But, if I had needed to change the axis limits I would use the following command

axis( [ XMin XMax YMin YMax ] );

Next I want to change the tick marks. Right now there tick marks on the y-axis are shown for every multiple of 5 and there is a tick mark at every integer value shown along the x- axis. In both cases the tick marks point in.

I prefer the tick marks to point outward, and I want to choose where the Tick Marks are positioned.

set(gca, ‘TickDir’, ‘out’, ‘XTick’, [1:10], ‘YTick’, [0 10 20 30]);

Notice the tick marks along the y-axis are now positioned at `y = {0, 10, 20, 30}` and the tick mark positions the x-axis haven’t changed. Both sets of tick marks also point outward.

Now that the basic figure properties are looking pretty good, I want to add axis labels so that my figure can be interpreted. This is achieved with two lines of code.

xlabel( ‘Time (Days)’, ‘FontSize’, 16 );
ylabel( ‘Population in Millions’, ‘FontSize’, 16, ‘Rotation’, 90 );

and my resulting figure looks like

Notice that I am able to control the size of the font, and I also can change the rotation of the y-axis label. If I had not included the 90 degree rotation factor, then the y-axis label would have overrun the plot. Zooming in on the x-axis shows the full effect

### Step 4: Save the figure as an eps file

Once you are happy with the figure you have produced in MATLAB you’ll need to save it as an eps file (especially if you are writing your paper in LaTeX). Note that if you are using MS Word, it is best to save your figure as a jpg file.

saveas(fh, ‘FruitflyPopulation’, ‘epsc’);

Recall that ‘fh’ is the figure handle of Figure 1, and note that the ‘epsc’ command saves a color eps file. Yes, I know that my figure doesn’t use colors, but for some reason using the ‘epsc’ command produces the nicest looking figures. Now I don’t have to look at that MATLAB Figure window, and I am left with a nice looking (publication quality!) figure made in MATLAB.

Now, using all (or any combination) of the commands described above you can create your own publication quality figure. Simply place the commands in a one M-file and with a single click of the mouse you’ll have a great looking figure for your next paper.

When generating figures for publication from within Matlab, one annoyance (of many!) is the unnecessary whitespace that Matlab introduces. One would prefer Matlab to make the bounding box as tight as possible and let LaTeX handle the whitespace.

It turns out that an "axes" in Matlab has three properties which determine its positioning: OuterPosition, Position, and TightInset. OuterPosition gives the coordinates of the entire region within the current figure belonging to the axes. Position gives the region contained by the "data" region of the axes. TightInset gives the distance beyond this "data" region which is used by tick marks, labels, titles, and other decorations. Here's a sample plot with the OuterPosition illustrated in yellow, the Position in magenta, and the TightInset in red:

Notice the space between the red rectangle and the boundary of the image. Why is that there? We can eliminate it by setting Position to be equal to OuterPosition minus the margins given by TightInset:

```set(gca, 'Position', get_r(gca, 'OuterPosition') - ...      get_r(gca, 'TightInset') * [-1 0 1 0; 0 -1 0 1; 0 0 1 0; 0 0 0 1]);```

That little matrix is there because OuterPosition and Position are stored as `[x_0 y_0 width height]` whereas TightInset is ```[dx_left dy_bottom dx_right dy_top]```. The results are:

Voilà! The offending whitespace has been removed. (For some reason, however, Matlab, seeing your modification of Position, takes it upon itself to compute a new, nonsensical value of OutsidePosition. This seems to be harmless...)

Another annoyance is in getting your figure to be the right size. Sure, you can scale your figure, but then the fonts will be the wrong size. The easiest thing to do is to estimate the desired size of your final figure, and have Matlab generate the figure in the correct size to begin with. The trick is to force not just the PaperSize but also the PaperPosition. If we want a figure 6.25 inches by 7.5 inches, we would do this:

```set(gcf, 'PaperUnits', 'inches'); set(gcf, 'PaperSize', [6.25 7.5]); set(gcf, 'PaperPositionMode', 'manual'); set(gcf, 'PaperPosition', [0 0 6.25 7.5]);```

A yet further annoying situation is this: you dutifully utilize PDF or EPS files for your figures, and yet they appear to be included as ugly, non-scalable raster graphics! I encountered this problem just today. Matlab allows you to choose between several renderers, which determine just how your figures get made. Suppose you have utilized transparency in your figure, yet are asking Matlab to output a figure to PDF, which (in the version supported by Matlab) does not support transparency. What's Matlab to do? Here's what it does do: it takes a screenshot, producing a bitmap, which is then wrapped in EPS or PDF. Doh!

The trick is to ask Matlab to use the "painters" renderer. It does not support transparency, but at least you're guaranteed vector graphics output:

```set(gcf, 'renderer', 'painters'); Finally, just for the sake of completeness, you might want to actually generate your output file: ```print(gcf, '-dpdf', 'my-figure.pdf');
print(gcf, '-dpng', 'my-figure.png');
print(gcf, '-depsc2', 'my-figure.eps');

• 评论加载中，请稍候...

验证码： 请点击后输入验证码 收听验证码

发评论

以上网友发言只代表其个人观点，不代表新浪网的观点或立场。

新浪BLOG意见反馈留言板　不良信息反馈　电话：4006900000 提示音后按1键（按当地市话标准计费）　欢迎批评指正

新浪公司 版权所有