# Making Pretty Graphs102

Posted by Loren Shure,

Today I’d like to introduce a guest blogger, Jiro Doke (email: Jiro.Doke@mathworks.com), who is an applications engineer here at The MathWorks. He used MATLAB in his life prior to The MathWorks, and one of his interests is data visualization.

### Contents

In my graduate work, I used MATLAB extensively for doing analysis and visualization. Often times, the plots that I created were used for my publications. It was then when I started to explore the flexibility of Handle Graphics to customize MATLAB plots in order to create publication-quality graphics. Ultimately, I was able to use MATLAB almost exclusively for my plots.

Let me walk you through the step-by-step process of how I did it. I'm using some fabricated data, but the plot is very similar to the ones I generated for my research.

load data

### Create Basic Plot

First, I plot my data to create the crude visualization

figure('Units', 'pixels', ...
'Position', [100 100 500 375]);
hold on;

hFit   = line(xfit  , yfit   );
hE     = errorbar(xdata_m, ydata_m, ydata_s);
hData  = line(xVdata, yVdata );
hModel = line(xmodel, ymodel );
hCI(1) = line(xmodel, ymodelL);
hCI(2) = line(xmodel, ymodelU);

Next, I do my first-round modification of my plots. At this point, I'm not worried about the esthetics yet.

set(hFit                          , ...
'Color'           , [0 0 .5]    );
set(hE                            , ...
'LineStyle'       , 'none'      , ...
'Marker'          , '.'         , ...
'Color'           , [.3 .3 .3]  );
set(hData                         , ...
'LineStyle'       , 'none'      , ...
'Marker'          , '.'         );
set(hModel                        , ...
'LineStyle'       , '--'        , ...
'Color'           , 'r'         );
set(hCI(1)                        , ...
'LineStyle'       , '-.'        , ...
'Color'           , [0 .5 0]    );
set(hCI(2)                        , ...
'LineStyle'       , '-.'        , ...
'Color'           , [0 .5 0]    );

To make it more publication-quality, I make the following changes to the line properties, including the errorbar widths. In my opinion, using thicker lines and larger markers greatly improves the "look" of my graphics. It's quite subjective, but I select them based on how much data is on the graph. I select the appropriate "crowdedness" (balance of dark and white space):

set(hFit                          , ...
'LineWidth'       , 2           );
set(hE                            , ...
'LineWidth'       , 1           , ...
'Marker'          , 'o'         , ...
'MarkerSize'      , 6           , ...
'MarkerEdgeColor' , [.2 .2 .2]  , ...
'MarkerFaceColor' , [.7 .7 .7]  );
set(hData                         , ...
'Marker'          , 'o'         , ...
'MarkerSize'      , 5           , ...
'MarkerEdgeColor' , 'none'      , ...
'MarkerFaceColor' , [.75 .75 1] );
set(hModel                        , ...
'LineWidth'       , 1.5         );
set(hCI(1)                        , ...
'LineWidth'       , 1.5         );
set(hCI(2)                        , ...
'LineWidth'       , 1.5         );

hE_c                   = ...
get(hE     , 'Children'    );
errorbarXData          = ...
get(hE_c(2), 'XData'       );
errorbarXData(4:9:end) = ...
errorbarXData(1:9:end) - 0.2;
errorbarXData(7:9:end) = ....
errorbarXData(1:9:end) - 0.2;
errorbarXData(5:9:end) = ...
errorbarXData(1:9:end) + 0.2;
errorbarXData(8:9:end) = ...
errorbarXData(1:9:end) + 0.2;
set(hE_c(2), 'XData', errorbarXData);

No plot is complete unless it is well annotated.

hTitle  = title ('My Publication-Quality Graphics');
hXLabel = xlabel('Length (m)'                     );
hYLabel = ylabel('Mass (kg)'                      );

hText   = text(10, 800, ...
sprintf('\\it{C = %0.1g \\pm %0.1g (CI)}', ...
c, cint(2)-c));

hLegend = legend( ...
[hE, hFit, hData, hModel, hCI(1)], ...
'Data (\mu \pm \sigma)' , ...
'Fit (\it{C x^3})'      , ...
'Validation Data'       , ...
'Model (\it{C x^3})'    , ...
'95% CI'                , ...
'location', 'NorthWest' );

### Adjust Font and Axes Properties

Since many publications accept EPS formats, I select fonts that are supported by PostScript and Ghostscript. Anything that's not supported will be replaced by Courier. I also define tick locations, especially when the default is too crowded.

set( gca                       , ...
'FontName'   , 'Helvetica' );
set([hTitle, hXLabel, hYLabel, hText], ...
'FontName'   , 'AvantGarde');
set([hLegend, gca]             , ...
'FontSize'   , 8           );
set([hXLabel, hYLabel, hText]  , ...
'FontSize'   , 10          );
set( hTitle                    , ...
'FontSize'   , 12          , ...
'FontWeight' , 'bold'      );

set(gca, ...
'Box'         , 'off'     , ...
'TickDir'     , 'out'     , ...
'TickLength'  , [.02 .02] , ...
'XMinorTick'  , 'on'      , ...
'YMinorTick'  , 'on'      , ...
'YGrid'       , 'on'      , ...
'XColor'      , [.3 .3 .3], ...
'YColor'      , [.3 .3 .3], ...
'YTick'       , 0:500:2500, ...
'LineWidth'   , 1         );

### Export to EPS

I set PaperPositionMode to auto so that the exported figure looks like it does on the screen.

set(gcf, 'PaperPositionMode', 'auto');
print -depsc2 finalPlot1.eps
close;

### Postprocess

This looks great! One thing that I may want to change is the way the dotted and dashed lines look. Notice that the dots are too small. So, I wrote a simple function that goes into the EPS file and modifies the line definitions. I have posted the function, fixPSlinestyle, on the File Exchange.

fixPSlinestyle('finalPlot1.eps', 'finalPlot2.eps');

And there you go. I have automated the process of creating publication-quality graphics. Handle Graphics give you advanced control of how graphics look. In case you didn't know, MATLAB allows you to quickly take a MATLAB script and publish a formated report (HTML, Word, LaTeX, XML, PPT), where the figures are automatically converted to various graphics format, including EPS. This document was created using publish.

Tell us here about some of the cool things you do with Handle Graphics to make your figures look prettier.

Get the MATLAB code

Published with MATLAB® 7.5

mut replied on : 1 of 102

hi all:

I would like you to comment on how to create eps from figures that have surfaces, lines and text objects, overlaping or not, that meet publication standards.

Last month i have some troubles (big ones) doing it.

see you

mut

Jiro Doke replied on : 2 of 102

Hi mut,

print -deps

should work with figures that have surfaces and text as well. The overlapping could be affected by the order in which you create the object. If you create a text object and then create a patch over it, it won’t show the text, but the text object will still be in the EPS file hidden under the patch object.

What kind of troubles were you having?

John McDermid replied on : 3 of 102

Would you comment on the following code segment

hText = text(10, 800, …
sprintf(‘\\it{C = %0.1g \\pm %0.1g (CI)}’, c, cint(2)-c));

I am particularly interested in the \\it{…} syntax. I suspect that this is a TEX command but I could not find reference to it in the manual.

Jiro Doke replied on : 4 of 102

John,

Yes, it is a TeX markup. Ultimately, what I wanted was

\it{C = ### \pm ### (CI)}

\it and \pm are TeX commands for italicizing and the plus/minus sign. See here for the TeX table:

http://www.mathworks.com/access/helpdesk/help/techdoc/ref/text_props.html#String

However, there’s a slight twist here that I am using SPRINTF to construct the string. Since I don’t want SPRINTF to evaluate the “\” character, I have “\\”.

BTW, I was just told that the standard syntax is:

sprintf(‘{\\itC = %0.1g \\pm %0.1g (CI)}’, c, cint(2)-c)

(note the braces outside of \\it).

mut replied on : 5 of 102

hi all:

jiro: try this simple print of a 3d object

hfig = figure;
aa = membrane;
surf(aa)
print -depsc -painters fig_painters.eps
print -depsc -opengl fig_opengl.eps

i use GSview to see my eps files.

in fig_painters.eps, when you increase the zoom, (no problem because this is a vector graphics) you can see the text objects drawned perfectly, but the surface object gets printed with some strange black dots (at my office computer, they are white), it depends of the graphics card you are using.

in fig_opengl.eps you can see the difference of using opengl as renderer. the surface gets printed nicely, on the other hand, the text and line objects get an staircase effect.

until now, no one from mathworks could explain me why this is happening (it is happening since at least from matlab 5.3, my first matlab version), could it be malfunctioning software???.

they showed me some work around, like getting exportfig function to print two different eps files, one with the surface objects rendered with opengl, and a second one rendered with painters with the text objects, and then merge the two eps files with epscombine or overlap them at the word processing software… well they are work around…

hope this time someone could explain me properly why is this happening…..

see you

Will Robertson replied on : 6 of 102

@mut The problem is that the renderers that support shading and transparency are bitmap based, not vector. Matlab uses a single renderer for an entire figure, so OpenGL is also used to create the axes and text in the figure.

But you really want vector output for the text and axes, which is why the epscombine method is necessary.

Note that you can mitigate the staircase problem a little bit by increasing the resolution of the output, but this will create much larger graphics files. Until The Mathworks decides to clean up the way these figures are exported, the exportfig+epscombine approach is the best way around the problem.

If you run into troubles with epscombine, please let me know :)

Marcelo replied on : 7 of 102

Nice post. Matlab is really powerful to create nice looking figures. I created all the figures in my PhD
thesis using Matlab. I prefer though the png format. The quality is great, the file size is small, and it
works with pdflatex.

Cheers,

Marcelo

Marcelo replied on : 8 of 102

I forgot to ask: where did you get this AvantGarde font? Is it free?

Jiro Doke replied on : 9 of 102

AvantGarde is a Postscript/Ghostscript font. I believe you get it with Ghostscript.

http://www.mathworks.com/access/helpdesk/help/techdoc/creating_plots/f3-103191.html#f3-96850

Try this and see if you get the 11 fonts:

text(0.1, 0, ‘This is AvantGarde’, ‘FontName’, ‘AvantGarde’);
text(0.1, 0.1, ‘This is Bookman’, ‘FontName’, ‘Bookman’);
text(0.1, 0.2, ‘This is Courier’, ‘FontName’, ‘Courier’);
text(0.1, 0.3, ‘This is Helvetica’, ‘FontName’, ‘Helvetica’);
text(0.1, 0.4, ‘This is Helvetica-Narrow’, ‘FontName’, ‘Helvetica-Narrow’);
text(0.1, 0.5, ‘This is NewCenturySchlbk’, ‘FontName’, ‘NewCenturySchlbk’);
text(0.1, 0.6, ‘This is Palatino’, ‘FontName’, ‘Palatino’);
text(0.1, 0.7, ‘This is Symbol’, ‘FontName’, ‘Symbol’);
text(0.1, 0.8, ‘This is Times-Roman’, ‘FontName’, ‘Times-Roman’);
text(0.1, 0.9, ‘This is ZapfChancery’, ‘FontName’, ‘ZapfChancery’);
text(0.1, 1, ‘This is ZapfDingbats’, ‘FontName’, ‘ZapfDingbats’);
ylim([-0.1 1.1]);
print -depsc2 fonttest.eps

Jiro Doke replied on : 10 of 102

Marcelo,

Thanks for your comment. Do you save your PNG at a high resolution? I love using PNG for presentations, but if I want anti-aliasing, I have to save it at a high resolution and then shrink it.

Marcelo replied on : 11 of 102

Jiro,
I have Ghostscrip but not this font.

About the png, I do like this, to get a good resolution: print(‘-dpng’,’-r300′,…

Alexandra replied on : 12 of 102

Thank you so much for this blog entry. It’s exactly what I needed! I have a few questions:

1. I find that grayish markers don’t print well in bw, even on a LaserJet. Is there a better option for the “validation data” markers in your plot?

2. Is there a workaround to include TeX in a legend entry? That would be fabulous.

3. Is there a per mille sign that can be used in MATLAB?

4. I used exportfig and epscombine, mentioned in other comments, to get a good quality plot. They’re great! I did get an error when trying to give a tight bounding box though. I often have a problem with my xlabel being cut off when I export. Out of habit, I use the Export Setup GUI. Is the command line print (or exportfig) a better option?

Thanks a million!

Jiro Doke replied on : 13 of 102

Hi Alexandra,

1. Yes, for BW or grayscale output, I would select a better ‘color’ property that would show well in those output formats. Maybe a darker shade of gray and also set the ‘MarkerEdgeColor’ to be dark.

2. I’m not sure I understand. In the blog, some of the legend text contain TeX (\mu \pm \sigma). Do you want to display them without using TeX?

3. I searched around and found that “char(8240)” creates the per mille sign. e.g. [‘5 ‘, char(8240)]

4. The Export Setup GUI allows you to change many of the settings via the GUI, so it may be more easy to use. To do the equivalent with “print” (or exportfig), you would specify those settings via command line. Export GUI ultimately calls “print” with the appropriate settings under the covers.

K. Hamed replied on : 14 of 102

Concerning how lines look in the ps file. I learned a trick from a friend some time ago. If I replace the line which says “0 cap” in the postscript file with “1 cap”, the edges of lines appear round. This gives thick lines and dots a nicer look. Any comments?

P.S. I posted the same comment on the file exchange for the file “fixPSlinestyle.m”. sorry for the duplication, but I thought it may be more useful if I post it here also.

Jiro Doke replied on : 15 of 102

K. Hamed,

I think “setlinecap” does that. 0 for straight edge (butted), 1 for rounded, and 2 for projected. Search google for postscript reference pages, In some (many?) cases, the file defines abbreviations, such as “cap” for “setlinecap”.

Alexandra replied on : 16 of 102

1. I know that some publications charge extra for color, so it’s best to create bw or grayscale plots. I’ll try messing with the MarkerEdgeColor.

2. Oops, I meant that I want to use TeX in ticklabels. For example, it’d be great to label xaxis ticks with pi/2, pi, etc. with the TeX symbols. I also tried using
‘Interpreter’,’latex’ but that doesn’t work either.

3. Yes I can get the permille sign to show up on the command line, but this doesn’t work in the figure. For example

xlabel([‘5 ‘,char(8240)])

gives me something like 5 “s. And when exporting to an eps I get yet something else! It turns out to be an a with a hat and a degree symbol.

I can’t wait to try the fixPSlinestyle for those pesky dashdotted lines! I could have used this in my thesis…

Thanks!

Alexandra replied on : 18 of 102

Jiro,

Thanks for the link to format_ticks. It basically automates what I had done once with text commands. At least this saves me some time!

About permille, I’m using MATLAB 7.3.0.298 (R2006b) in Linux. I set the default font to times, but changing that doesn’t seem to make a difference. I know of someone else who also has had this problem (also in Linux).

Thanks!

Jason replied on : 19 of 102

@Alexandra,

There is is a problem in the way Matlab creates the output with the permil character. There have been a few posts about it in the newgroup. The only workaround I have found it to hand edit the EPS file.

Here is an example of a basic plot(x,y) where I had the permil character on the y-axis and how I fixed the problem (this is in my Service Request # 1-3ZGSEO):

I have found a fix for this bug. The key is in the encoding. Matlab is incorrectly using the \ISOLatin1Encoding for the permil character. It should be using \StandardEncoding for it.

This is how Matlab creates the EPS file:

%%IncludeResource: font Helvetica
/Helvetica /ISOLatin1Encoding 192 FMSR

255 1708 mt -90 rotate
($\342\200\260$) s
90 rotate

It should be:

%%IncludeResource: font Helvetica
/Helvetica /StandardEncoding 192 FMSR

255 1708 mt -90 rotate
( $\275$) s
90 rotate

hhb replied on : 20 of 102

does anyone know how to generate a hat above a symbol in a matlab figure:

For instance, I tried this one and it doesn’t work:

\hat{beta}

Thanks a lot

Jiro Doke replied on : 21 of 102

text(0.5,0.5,’$$\hat{\beta}$$’, ‘interpreter’, ‘latex’)

Mukhtar Ullah replied on : 22 of 102

I found this blog extremely useful which inspired me to rewrite some of my files. I have found a very strange problem: For small ([8 6] cm) figures, my Xlabel and YLabel (if rotation=0) get cutoff if I use the print command while there is no prolem when I export pdf from GUI.
I have tried both print and command version of saveas for both pdf and eps. Only the GUI export to pdf (not eps) works fine. Is it a bug or I am missing something?

Thanks.

Jiro Doke replied on : 23 of 102

Do you have a short example code that you can post to reproduce the behavior you’re describing? I did this and I don’t see any clipping using the PRINT command:

figure(…
‘units’, ‘centimeters’, …
‘outerposition’, [0 0 8 6], …
‘paperpositionmode’, ‘auto’);

plot(rand(10,4));

xlabel(‘time (sec)’);
ylabel(‘value (m)’);
title(‘Small Figure’);

print -depsc myEPS.eps

Achilleas Samaras replied on : 24 of 102

Hi!

I’ve been working on MATLAB for a while and I wonder if you could help me with something…

I have plotted a contourf graph with the wave height distribution in a coastal area and I would like now to plot -in the same graph- the wave direction vectors as well…

Any idea how this could be achieved????

I would be grateful for any advice.

Achilleas Samaras

Mukhtar Ullah replied on : 26 of 102

Jiro Doke, Thank you for your response. The problem starts when I use latex inerpreter for axis labels.

xlabel(’$t$’);
ylabel(’$y(t)$’);

Somehow the latex interpreter adds extra space to the text objects.

Mukhtar

Mukhtar Ullah replied on : 27 of 102

Another problem with LaTeX interpreter is that the spacing between legend lines becomes very large which destroys the look of your figure (again in small sizes). I can control the length of the legend lines, their linewidth but I have no idea how to reduce the spacing among the lines.
Thanks

Matthew Davis replied on : 28 of 102

I’m a long time user of matlab (1994) and am still learning new tricks…. managed to teach myself a lot of handle graphics tricks over the years.

I came across this blog while searching for a solution to massive file sizes with bitmapped graphics but retaining decent looking fonts. I have used exportfig to generate separate files for the graphicsand the text… one as a jpg, the other as eps. I can then use eg jpeg2eps to convert the jpg to eps, but I haven’t been able to work out how to subsequently combine the two files.

epscombine seems written specifically for when both files are output directly by MATLAB to eps.

Any hints?

Of course, a solution would be for matlab to have this functionality itself….

Thanks, Matt.

Jiro Doke replied on : 29 of 102

Hi Matthew,

I don’t have too much experience with large bitmap graphics, but is the reason you are exporting to jpg first and then converting to eps using jpeg2eps, because it is smaller in file size than if you created eps directly using exportfig?

Yes, I agree it would nice for MATLAB to have this functionality. Thanks for the feedback. I’ll relay this back to our developers.

Hi Mukhtar,

I was able to reproduce the same problem. I think it’s best for you to contact our tech support (http://www.mathworks.com/support/), as I don’t have a good explanation for this.

Staffan Backén replied on : 30 of 102

Hello Matthew –

I managed to pull of the stunt you are talking about (big bitmap and nice fonts) – but it did involve some hand editing. The way I did it:
generate two figures, one with only data (in my case, a big 3D mesh with several million samples), and one with only axes, titles, labels etc.

Make sure they are have identical sizes and save both as .eps. Then, they have to be merged manually (basically, put the axes/text part after the bitmap) and I do not recommend this if you have no prior experience of postscript/eps. Also, the final .eps file turned out to be huge. Acceptable size after conversion to .pdf using ghostscript though. (I think pdf have a way more efficient method of storing bitmaps)

I would love it if matlab would retain the fonts/axis when printing to eps, but I assume this might require an overhaul of the “print” function?

Regards,
Staffan

Jiro Doke replied on : 31 of 102

Hi Staffan,

For what you have just described, these utilities on the File Exchange will make it easier:

%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
surf(peaks(100),’facealpha’,.7,’LineStyle’,’none’);

xlabel(‘My X Label’);
ylabel(‘My Y Label’);
zlabel(‘My Z Label’);

exportfig(gcf,’myExported’,’separatetext’,1,’color’,’rgb’);

epscombine(‘myExported_t.eps’,’myExported.eps’,’myCombined.eps’);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Staffan Backén replied on : 32 of 102

Thanks Jiro –

That sure made it easier :) – and, it is actually a method I can recommend to others (who may not be as big fans of postscript as myself …).

Regards,
Staffan

Mukhtar Ullah replied on : 33 of 102

Hi Jiro Doke,
Thank you for your suggestions. I could not find any satifactory solution in the support site (may be I don’t know how to make best use of that). However I managed to come with a stable solution for 2-D plots which I will post soon. In fact I have written a file which gives a set of function handles for various tasks. Everything is inspired by this blog.

Mukhtar

Mukhtar Ullah replied on : 34 of 102

As I mentioned in my last post, I have submitted a function SETAXES to the ML file exchange today (should appear in 2-3 days). I have tried to incorporate the nice lessons I learned from this blog into that function. I hope users find it useful.

Mukhtar

Jiro Doke replied on : 35 of 102

Hi Mukhtar,

Thanks for posting your entry to the File Exchange. It’s very nice.

The developers here at the MathWorks are aware of some of these issues that we talked about in this blog. Thanks for contributing your ideas.

jiro

Michel Slivitzky replied on : 36 of 102

Sorry for being slightly off topic abut I have followed this blog for number of weeks and always found very usefull information.

I am using version 2007b on both a windows system and OSX10.4.
In windows I have set the preferences/copy option to “set white background” for cut/paste to my Word document.

However in OSX10.4 I did not find a similar option in the references.

Is there a way to end up with a white background ?

Nichel

Mukhtar Ullah replied on : 37 of 102

Michel,
I am not familiar with OS but it should be possible from the command line; Type this after you are finished with your figure

set(gcf, ‘Color’, ‘w’)

Mukhtar

Michel Slivitzky replied on : 38 of 102

removing title and labels apaces in pictures

I am creating a picture with the following 4 instructions:

scrsz = get(0,’ScreenSize’);
figure(‘Position’,[0 0 804 800]);
image(AA)

It it possible to completely remove the spaces (“margins” used by the title and labels. I have to crop each picture to remove these “margins” when copy/paste ot print the picture.

Jiro Doke replied on : 39 of 102

Michel,

In your example, is the size of the image 804 by 800? You can set the axes to be the same size as the figure, thereby making it the same size as the image:

set(gca, ‘Units’, ‘normalized’, ‘Position’, [0 0 1 1]);

Michel Slivitzky replied on : 40 of 102

Jiro,

in this case the absolute size is not of prime importance. What I need is to preserve the aspect ratio of the .jpg file I am reading, which in this particular case is 844 by 840 pixels.

What is the best way to achieve it ?

Jiro Doke replied on : 41 of 102

Michel,

So I see two issues: one is the aspect ratio, and the other is the white margins you speak of when you copy/paste.

imSize = size(AA);

% to ensure no white (blank) space
figure(‘Position’, [0 0 imSize([2 1])]);
image(AA)
set(gca, ‘Units’, ‘normalized’, ‘Position’, [0 0 1 1]);

% to ensure correct aspect ratio
% this may not be necessary since the axes/figure size
% is set to image size
axis image

Jiro Doke replied on : 42 of 102

Michel,

This is assuming you don’t have the Image Processing Toolbox. If you use “imshow” of IP Toolbox, it takes care of aspect ratio.

Michel Slivitzky replied on : 43 of 102

Jiro,

Following your example I get the following error :

??? Error using ==> set
Bad value for axes property: ‘Units’.

Error in ==> carte_pval at 36
set(gca,’Units’,’normalised’, ‘Position’, [0 0 1 1]);

what am I doing wrong ? I am lost

Michel Slivitzky replied on : 44 of 102

Jiro
it was just a typo in “normalized”

Stephen Romaniello replied on : 45 of 102

With regard to the per mille symbol for MatLab under Windows, an easy solution is to paste the per mille character from the appropriate font family in the Character Map directly into the string text in the figure window. It’s low tech, but it gets the job done for users who need to add this one symbol quickly.

Achilleas Samaras replied on : 46 of 102

Hello everybody!

I’ve been working on MATLAB for a while and I wonder if you could help me with something…

I’m trying to increase the arrow-head size in a quiver plot. Despite the fact that I’m increasing the “MaxHeadSize” value, the arrows do not seem to change.

Moreover, can I somehow change the marker at the head of the line? Or make the arrow filled or bold? Because some of my arrows are pointing North and the arrow-heads are hardly discernible.

I would be grateful for any advice!

Achilleas Samaras

Stephen Romaniello replied on : 47 of 102

Here’s a question for Loren, Jiro, and all.

When using inward tick marks with surfaces and view(0,90), the surfaces cover the tickmarks if the surface extends past the limits of the axes (as with Clipping). This is apparently regardless of the depth (ZData) of the surface in the figure.

Does anyone have a work around for this? In the end, I want a colored x-y surface, with visible, inward tick marks, even when the surface extends past the current limits of the figure.

Jiro Doke replied on : 48 of 102

@Achilleas,

I tried to increase the arrow size and it didn’t work for me as well. I’m asking around to see if there’s a way to get it to work. I’ll let you know if I hear anything.

@Stephen,

Can you show me a snippet of code that illustrates this. I think I understand what you mean, but it would be nice if you had a simple example of this so that I can show it to the developers.

Jiro Doke replied on : 49 of 102

Hi Stephen,

I just learned about this property myself, but there’s an axes property called ‘Layer’, which allows you to bring the axes to the top.

set(gca, ‘Layer’, ‘top’)

Adam replied on : 50 of 102

I want to make an axis label using the latex interpreter, the following command works fine on a plot made with plot(…), but when I apply it to a surf(…) plot it does NOT!

ylabel(‘$2\pi\Phi/\Phi_0$’,’interpreter’,’latex’)

If I don’t use the latex interpreter, my Phi’s get cut off on their sides… please help!

LQ replied on : 51 of 102

Great stuff. Is there a ‘per thousand sign’ in Matlab? I mean the sign looks like ‘%o’.

Thank you.

Jiro Doke replied on : 52 of 102

LQ,

Is “per thousand” the same thing as “per mille”?

Then, this will do:

xlabel([’5 ‘,char(8240)])

Michel Slivitzky replied on : 53 of 102

How can I add a title centered above subplots and specify the fontsize

Michel Slivitzky replied on : 55 of 102

Thanks Loren,

have tried this code which has problems with proper centering.

Could probably be corrected by patching this code; have tried but without results

beyond my present expertise

Diego Arosio replied on : 57 of 102

Hi everybody,
is there a way to set margin size when printing a figure to a file?
I’ve been looking around, but I only found out how to set margins when printing to paper.
Thank you

David P. replied on : 58 of 102

Jiro,

I want to publish my data to a Word file. Every time I do this the format is different from the basic figure, in that axis labels overlap with tickmarks or the axis areas stretch or shrink.

What do I need to do so that I can consistently get the output that I am looking for.

Jiro Doke replied on : 59 of 102

David,

One thing you can try is to set the PaperPositionMode of the figure to ‘auto’. Search for “PaperPositionMode” in the DOC to learn more about it.

Andrew replied on : 60 of 102

Hi there,
It is time to write my thesis and I am having some difficulty exporting my figures in the way I want. First, I am using pdflatex and hence cannot use psfrag or the equivalent to alter the font of the axes labels etc in my Matlab figures. The Matlab export set-up does a nice job, converting everything to a given font, but I cannot get the computer modern fonts (the default font of latex) ‘cmr’ to work in the export set-up. Simply nothing happens as though it does not support the font. However, in the figure editor the ‘cmr’ fonts work so it does not seem to be the case that Matlab simply doesn’t support computer modern fonts. Any ideas ?

Richard Layton replied on : 61 of 102

I cannot figure out how to change the line-spacing in multiple-line xlabels, ylabels, and text in a MATLAB figure. The default is apparently a line-spacing of 1.2.

Chris replied on : 62 of 102

How can I reformat a plot legend to contain both rows and columns of legend entries? Creating a plot of 10 sets or more of data causes the standard legend to grow large and overlap major portions of my figure. I would instead like a legend set up in the form of a matrix with entries like:

dataset1 dataset2 dataset3 dataset4
dataset5 dataset6 dataset7 dataset8

The only orientation options available are ‘Horizontal’ and ‘Vertical’ which either place the legend entries in a single long row or column.

Jiro replied on : 63 of 102

Chris,

There is no way of doing this using the “legend” command. I have entered this as an enhancement request.

Ulla Vainio replied on : 64 of 102

That error bar width adjustment was extremely useful and I would never have figured it out myself. Perhaps some day the width could be included in the errorbar-function as an option? Normally I have the problem that the error bar width is way too wide so that the the graph looks really messy.

Ljubomir Josifovski replied on : 65 of 102

I have a simple figure where the legend overlaps with the plot after it is created, but when streched with set(gcf, ‘units’, ‘normalized’, ‘outerposition’, [0 0 1 1]) looks ok. My problem is that print(gcf, ‘-dpng’, dumpFileName) dump to file does not hounour my “stretching” (it dumps the figure with the overlapping legend). Now if I stretch it and then do manual File-SaveAs from the figure GUI menu it saves it as I want it (stretched). Anyone know how can I achieve the same in batch mode?

Regards,
Ljubomir Josifovski

Jiro replied on : 66 of 102

@Ljubomir,

Do this:

set(gcf, 'PaperPositionMode', 'auto')

Then when you save, it will preserve the look of the figure on the screen.

@Ulla,

Thanks for your input. I will submit an enhancement request for error bar width.

xdense replied on : 67 of 102

Hi,

How is it possible to stretch or to shrink a graph?
F.e. i got 5 graphs: one measured after 5 seconds, 2 after 6 secs, 3 after 7 secs.
Let us assume measureing stopped after reaching a predefined end-point.

How can I plot those 5 graphs “time-qualized”, e.g. by percentage: x should show proceeding until reaching 100% (so that time doesnt influence the view), y shows the measured value.

So it should be very helpful to stretch the 5-second-graph to the same length as the 7 secs graph to to be able to compare all graphs.

Alex

Loren replied on : 68 of 102

Alex-

Set the x-axis limits on all the plots to the values for the 7-second second plot. Look at xlim and axis functions.

–Loren

Mastaneh replied on : 69 of 102

Hi,
Your blog has been a great reference for me so far! :)
In your example, you have defined the ‘YTick” values linearly, and they actually correspond to the data values. Now, suppose that I have several subplots of normplot in one figure, and I want to display only a few Yticks on the y-axis (probablity), e.g. 0.001,0.50 and 0.999 -and I don’t know the corresponding data points.
My problem is that, after I specify them in a vector, Matlab considers them as the Data points, not the exact Tick labels. How can I resolve this problem?

Many thanks,

– Mastaneh

Jiro replied on : 70 of 102

Mastaneh,

It seems like “normplot” always creates 15 YTicks. If that’s the case, you can change the YTickLabel this way:

normplot(rand(1,1000));
ylab = {'0.001','','','','','','','0.50','','','','','','','0.999'};
set(gca, 'YTickLabel', ylab);


Hope this helps.

jiro

Thomas Ibbotson replied on : 71 of 102

One limitation to producing publication quality graphs in MatLab is the fact that errorbar only provides for errors in Y and not X. Although technically any error in x should be propogated into an error in y, it is often useful to be able to show x errorbars. When plotting two variables against each other in a scatter plot, which are not necessarily causally connected, x errorbars are essential.

Dear Jiro and Loren,

Thank you and other contributors for a fantastic thread. I followed several tips from the thread and got two great results:

1. I fixed a chronic problem with cutting-and-pasting MatLab figures using Mac OS X -> Preview -> Adobe illustrator CS. The problem was MatLab’s use of ISO encoding: I’m happy to expand if anyone else wants to know why fonts which look nice in MatLab come out mangled in Illustrator.

2. At last I have pleasantly dashed lines, and round caps on lines and points. Hooray! My eyes really are saying “thank you”.

For what it’s worth, in my local copy I added the following lines to Jiro’s code (the first five lines are his: they set the context):

% Open file and read it in
fid = fopen(varargin{1}, ‘r’);
str = char(str’);
fclose(fid);

%% The following lines fix MatLab’s font infelicity and square cap ugliness.

% Use standard (not ISO Latin) encoding
str = strrep(str, ‘ISOLatin1Encoding’, ‘StandardEncoding’);

% Set caps to rounded
str = strrep(str, ‘0 cap’, ‘1 cap’);

Ben replied on : 74 of 102

I have a scatter plot created with plot(x,y,’.’) with many data points, so the MarkerSize is quite small. As a result, it’s quite difficult to distinguish the colors in the legend. Can you help me overcome this? I’ve tried to increase the MarkerSize and/or change the Color of the text in the legend, using the handle array which is the second return value from legend, but Matlab seems to ignore all my efforts. If I instead change the attributes of the third return value, the changes show up in the legend but also in the main plot.

Help, please! I understand the value of keeping the legend in sync with the plot but surely it should be possible to have a different MarkerSize.

Jiro replied on : 75 of 102

Ben,

You’re pretty close. To get different effects in the legend, you should modify the second return value from LEGEND. But you should know which element of the handle array to modify. By doing GET on each of the element of the returned handle array, you’ll notice that the array is structured in this way:

legend text for line 1
legend text for line 2
...
line style for line 1
marker style for line 1
line style for line 2
marker style for line 2
...


With this in mind, you can change the marker size in the legend this way:

plot(rand(10, 4), '.');
[a,b,c,d] = legend('line1', 'line2', 'line3', 'line4');
set(b(6:2:end), 'MarkerSize', 20);



Hope this helps.

Joe P. replied on : 76 of 102

Paul R. Martin refers to “a chronic problem with cutting-and-pasting MatLab figures using Mac OS X -> Preview -> Adobe illustrator CS”. I am having a problem generating pdf figures to use with pdflatex. If I export to .pdf directly (on a Mac) the curves look jagged, so I have been exporting to .eps and then using Apple Preview to convert to .pdf. Recently (since OS 10.5?) the .pdf produced has slightly different fonts than the .eps, for example making them bold where they should not be. My work-around is to export to .eps, open in Adobe Illustrator, and then save as .pdf.
Paul – is this the problem you refer to? If so, can you point me in the right direction of your solution? Thanks.

Joe

suresh replied on : 77 of 102

I would like to have a XY plot without the Yaxis and Yticks and i want to print the figure to eps file. Even If I put the Yaxis color to background color, in print output Yaxis becomes visible. I searched about this problem. But I couldn’t find any solution. If you can help me, that would be greatful.
thank you.

Jiro replied on : 78 of 102

Suresh,

This seems to work on my computer:

plot(rand(10,4))
set(gca, 'box', 'off');
set(gca, 'ytick', []);
set(gca, 'ycolor', get(gcf, 'color'));
print -depsc test.eps


Sean replied on : 79 of 102

Great thread Jiro. I do have one suggestion for all the latexers out there though–switch to PDFLatex!!! It will make your lives many times easier and your documents better looking. MATLAB’s pdf generator (at least from the GUI) gives great results that are (best I can tell) 100% compatible with Adobe. This means you can open them directly in Illustrator (which saves as PDF with zero loss and stays vector!) and you can place them into your tex docs with no problem.

I realize that many of you out there may be .eps devotees, but this solution is much more workable than the multiple saves many people describe. Plus, I find that I am able to get the plots much better looking this way, and then if they require subtle editing, I can do it in Illustrator.

I guess the point I’m trying to make is that Latex (pdflatex that is) works great using just .pdf figures, and this is a great option because the .pdf format can store both vector and bitmap information (also, your text stays text this way, instead of rasterizing…), so I think it’s the way to go. EPS people will say that .eps does the same thing, but not really, because look how much trouble it is to create a decent looking .eps from MATLAB. Not to mention the fact that .eps files aren’t compatible with much at all and very few programs will open them.

So, I’m just saying, save yourself time and effort, get a better quality graphic that many programs can open–it’ll still be vector and you can avoid using 1980s technology.

Mat replied on : 80 of 102

Jiro, thanks for the great tutorial!

I have one question, though.
I have a problem with the minor and major tick thickness.
When I put my eps graph into my latex code, I can definitely see that the minor and major ticks have a different thickness and are a tiny bit (but noticeably) offset. Like in your last graph the 1000 kg tick for example. You can see that the minor tick is drawn over the major tick, has a different thickness and is a little offset.

Any help would be great

Mat

Martin Pedersen replied on : 81 of 102

I have problems generating new tick labels that contains LaTeX code. E.g. this simple example:

plot(1:10, 1:10);
set(gca,'XTickLabel','10^4');


It produces 10^4 instead of 10 raised to the power of 5.

I need this when chaning labels on a histogram. There no way in matlab do generate nice histograms of log binned data.

Any suggestions?

Martin

Lara replied on : 82 of 102

Hello!!!
I have some problems with quiver plot
When i’m ploting current I want only the arrowrs that shows the currents and not the markers.
I want to make markers invisible but i cannot understand how to do it.. yes i’m anew one Matlab user!!
any suggestions?

Lara

Jiro replied on : 83 of 102

@Martin,
I believe there is no way to have LaTeX formatting on labels, but I saw a few File Exchange entries that may help you.

@Lara,
I’m not completely sure I understand your description of what you want, but if you look at the documentation for QUIVER:

help quiver doc quiver

you’ll see some options to change the look for your quiver plot.

Jeremy replied on : 84 of 102

Jiro and Loren,

As others have said, great thread! This has been very helpful to me in getting my figures “up to snuff” using Matlab.

I referred back to this thread while I was having the same problem brought up in post 62 – I had 6 lines and my horizontal legend was overflowing off the page. In post 63, Jiro stated that this was not possible, but was put in as an enhancement request.

It does not appear that this functionality exists yet, but I found a work-around for this after some internet searching and playing myself. The solution is to create more than one set of axes, overlay them exactly, and make all but one of them transparent.

Here’s a simple example, using 4 lines (y1-y4) with the same set of x data (xdata). I’m assuming here that the data for y1-y4 and xdata have already been specified.


% Plot the first two sets of data
ph1(1) = plot(xdata,y1,'-ko','DisplayName','Y1 Legend Text');
hold on
ph1(2) = plot(xdata,y2,'-bs','DisplayName','Y2 Legend Text');

% Create the first legend
lh1 = legend(ph1,'Location','NorthOutside','Orientation','horizontal');
lh1_position = get(lh1,'Position');

% Now set any axis properties that you want (Font, Ticks, etc)
set(gca,'XLim',xlimits,'YLim',ylimits,'FontSize',18,'XTick',xticks,'YTick',yticks);

% Name the first axis ax1 and create a second axis on top of the first
ax1 = gca;
ax2 = axes('Position',get(ax1,'Position'));

% Plot the second two sets of data on ax2
ph2(1) = plot(xdata,y3,'-rd','DisplayName','Y3 Legend Text','Parent',ax2);
hold on
ph2(2) = plot(xdata,y4,'-g^','DisplayName','Y4 Legend Text','Parent',ax2);

% Again set any axis properties that you want (Font, Ticks, etc) to make sure that the Legend fonts are the same
set(ax2,'XLim',xlimits,'YLim',ylimits,'FontSize',18,'XTick',xticks,'YTick',yticks);

% Now, link the first axis to the second and make the second invisible
set(ax2,'Color','none','XTick',[],'YTick',[],'Box','off');

% Now make the second legend just below the first
lh2 = legend(ax2,ph2,'Orientation','horizontal');
lh2_position = lh1_position;
lh2_position(2) = lh1_position(2)-lh2_position(4);
set(lh2,'Position',lh2_position);


This should basically get you what you want, which is a legend in a matrix form:

    -o- Y1 Legend Text -s- Y2 Legend Text
-d- Y3 Legend Text -^- Y4 Legend Text


You may have to play around with the legend positions and options a bit to get things to look exactly like you want – I just directly set my legend positions for each legend instead of automatically setting it as I did in the above example code.

Anyways, since I spent so much time trying to get this right, figured I’d pass it on. Hope that works for others!

Jeremy

Loren replied on : 85 of 102

Jeremy-

Thanks for contributing back!

–loren

Jeremy replied on : 86 of 102

Sorry about the code in the previous post – apparently I didn’t enter the code fragments right for the blog.

The sample code begins at “% Plot the first two sets of data” and ends with “set(lh2,’Position’,lh2_position);”

Here it is more compressed:

% Plot the first two sets of data
ph1(1) = plot(xdata,y1,’-ko’,’DisplayName’,’Y1 Legend Text’);
hold on
ph1(2) = plot(xdata,y2,’-bs’,’DisplayName’,’Y2 Legend Text’);

% Create the first legend
lh1 = legend(ph1,’Location’,’NorthOutside’,’Orientation’,’horizontal’);
lh1_position = get(lh1,’Position’);

% Now set any axis properties that you want (Font, Ticks, etc)
set(gca,’XLim’,xlimits,’YLim’,ylimits,’FontSize’,18,’XTick’,xticks,’YTick’,yticks);

% Name the first axis ax1 and create a second axis on top of the first
ax1 = gca;
ax2 = axes(’Position’,get(ax1,’Position’));

% Plot the second two sets of data on ax2
ph2(1) = plot(xdata,y3,’-rd’,’DisplayName’,’Y3 Legend Text’,’Parent’,ax2);
hold on
ph2(2) = plot(xdata,y4,’-g^’,’DisplayName’,’Y4 Legend Text’,’Parent’,ax2);

% Again set any axis properties that you want (Font, Ticks, etc) to make sure that the Legend fonts are the same
set(ax2,’XLim’,xlimits,’YLim’,ylimits,’FontSize’,18,’XTick’,xticks,’YTick’,yticks);

% Now, link the first axis to the second and make the second invisible
set(ax2,’Color’,’none’,’XTick’,[],’YTick’,[],’Box’,’off’);

% Now make the second legend just below the first
lh2 = legend(ax2,ph2,’Orientation’,’horizontal’);
lh2_position = lh1_position;
lh2_position(2) = lh1_position(2)-lh2_position(4);
set(lh2,’Position’,lh2_position);

Rizwan replied on : 87 of 102

Good programe

Shivakumar Jolad replied on : 88 of 102

Thanks a lot for this nice blog article.
I have lot problems with producing such quality graphs. Can anyone help me with the following issues?
1. In the log-log plot, I could not get the ticks marks on x and y axis to stand out clearly. It is so weak that it is not clearly noticable in print.
2. Getting Latex characters/mini equations in axis label’s is really a pain. I couldn’t get simple stuff such $$\Delta M_g/sqrt{N}$$ to work. Subscripts dont align properly, cant get the characters to embed in the square root sign.

Any help from readers will be greatly appreciated.
thanks
Shiva

Dylan replied on : 89 of 102

@Sean, thanks for the suggestion to export to PDFs instead of EPS files!!! I was having a nightmare of a time trying to use Matlab figures in an Illustrator document because for some reason Matlab kept saving the EPS files with an unrecognized variant of Helvetica no matter what font I actually specified in my axes() declarations. Now, when I save to PDF files, they contain the correct fonts and Illustrator doesn’t balk and require me to manually go back in and change the font again.

Liz Küsel replied on : 90 of 102

Hi everyone,
I am trying to finish some plots for a paper and I am having problems with clipping of the x label. Here is what I am doing:

fullscreen = get(0,'ScreenSize')
figure('Position',[0 -50 fullscreen(3) fullscreen(4)])


Note that my screen size is 1680 x 1050. Then I use the plot command, label axes, and finally print to an eps file.

plot(Ec,Pavg,'k*','MarkerSize',20)
grid on
xlabel('Energy Flux Density (dB re 1\muPa^2 s )','FontSize',44)
ylabel('Average Detection Probability','FontSize',44)
set(get(gca,'XLabel'),'Position',[165 0.0030 0])
set(gca,'FontSize',36)
set(gcf,'PaperPositionMode','auto')
print -depsc -loose sl_probdet_test4.eps


If I choose a font size of 20, for example, everything looks fine but the fonts appear rather small on the eps file. This is a big issue because the journal will further shrink the figures and no one will be able to read the labels! However if I increase the font size to a “decent” size in terms of appearance, then when printing to eps the x label appears clipped at the bottom. I have tried many different things but so far was not able to overcome this problem.

I would really appreciate if anyone has any suggestions!
Thanks
Liz

Jack replied on : 91 of 102

Good suggestions for style. I know it’s just an example, but boy howdy would Tufte hate to see such an inky plot.

jiro replied on : 92 of 102

@Liz,
I couldn’t really run and test your code. For some reason, the xlabel didn’t even show up on my MATLAB figure. What I’ve done before for my journal publication is to use true units even in MATLAB. So instead of using ‘pixels’ or ‘normalized’, I use ‘inches’ or ‘centimeters’, even for label positioning, axes sizes, etc. And then I print using PaperPositionMode ‘manual’. This especially helps if you know what the final dimension is going to be in the journal. In the journals that I published to, they gave me the actual dimensions to be used.

@Jack,
What do you exactly mean by “inky plot”? Are you referring to the big dots and thick lines? When I used this style for my publication, the final plot was about 1.5×2 inches, so the lines and dots looked appropriate at that size. But I also wouldn’t claim to be an expert in visual design. ;)

sundar replied on : 93 of 102

Hi
When I set ‘DefaultlineMarker’ as ‘o’ in the startup.m file, and I plot a line with errorbars, even the errorbars get some kind of weird markers.
What should I do to set just the actual points with a particular marker?

jiro replied on : 94 of 102

@sundar,

ERRORBARs are created using line objects, so all the lines will show up with the marker that you specified. As you can see from this post example, you can return a handle from the ERRORBAR function, and use that to change the line properties. Note that you need to get the children of the handle to get the actual line handles:

set(0,'defaultLineMarker', 'o')
X = 0:pi/10:pi;
Y = sin(X);
E = std(Y)*ones(size(X));
h = errorbar(X,Y,E);
h2 = get(h, 'Children');

% Second handle is the handle to the error bar lines
set(h2(2), 'Marker', 'none');

Bert Buurman replied on : 95 of 102

Thank you very much for your explanation of how to make matlab figures look nice in latex. I was getting there but this really nailed it.

Gr.
Bert.

Lilia replied on : 96 of 102

Hello,

Thank you for all the helpful information.

I am currently trying to produce a nice looking plot for publication and I have run into something I don’t know how to do.

I have a set of strings as the tick labels along one of my axes and I would love to be able to assign different colors to different tick labels. Is that possible?

Thank you very much in advance.

jiro replied on : 97 of 102

@Lilia,

There isn’t a straightforward way of assigning different colors to different tick labels.

As a workaround, if you search on File Exchange for “tick labels“, you’ll find a number of entries that do some sort of customization on tick labels. You may be able to get some ideas from those entries. The idea would be to create individual text objects that are placed in the appropriate locations.

jiro replied on : 98 of 102

@Lilia,

Also, I would suggest searching and asking the question on MATLAB Answers.

Felipe G. Nievinski replied on : 99 of 102

Just for the record, the errorbar width issue is handled by FX submission # 22826, by Arnaud Laurent.

Hannah replied on : 100 of 102

Is there a way to set ‘PaperPositionMode’ to auto as a default, instead of setting it for each figure? set(0, ‘PaperPositionMode’, ‘auto’) doesn’t work.

Thanks
H

Hannah replied on : 101 of 102

Nevermind, I figured it out, put this in your startup.m file:

set(0, ‘DefaultFigurePaperPositionMode’, ‘auto’);

But on a related note, where can I find a list of these default properties (especially graph related ones) that can be set in the startup.m file?

jiro replied on : 102 of 102

@Hannah,