Loren on the Art of MATLAB

Making Pretty Graphs 102

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

First you might download the data.

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);

Adjust Line Properties (Functional)

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]    );

Adjust Line Properties (Esthetics)

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         );

% adjust error bar width
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);

Add Legend and Labels

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.

Your Examples

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

102 CommentsOldest to Newest

hi all:

i have been reading your blog since the beginning, great initiative!!!!

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

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?

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.

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).

hi all:

jiro: try this simple print of a 3d object

hfig = figure;
aa = membrane;
surf(aa)
shading interp
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

@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 :)

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

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

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.

Jiro,
I have Ghostscrip but not this font.

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

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!

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.

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.

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”.

Thanks for your comments, Jiro.

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!

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!

@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

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

How about this (using LaTeX)?

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

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.

Thanks for your comments, Mukhtar.

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

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

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

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

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.

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.

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

Hi Staffan,

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

http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectType=file&objectId=727
http://www.mathworks.com/matlabcentral/fileexchange/loadFile.do?objectId=16902&objectType=file

Here’s an example (once you have downloaded the above files):
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
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’);
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

Here are a couple of digest articles that talk about this:

http://www.mathworks.com/support/solutions/data/1-15IXD.html?solution=1-15IXD
http://www.mathworks.com/company/newsletters/digest/december00/export.html

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

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

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

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

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

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

removing title and labels apaces in pictures

I am creating a picture with the following 4 instructions:

AA=imread(‘E:\bassins.JPG’);
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.

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]);

Jiro,

Thanks for the reply,

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 ?

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.

AA = imread(…);
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

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.

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

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.

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

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.

@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.

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’)

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!

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

Thank you.

LQ,

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

Then, this will do:

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

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

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

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.

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.

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 ?

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.

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.

Chris,

Thanks for your comment.

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

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.

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?

Thanks in advance.

Regards,
Ljubomir Josifovski

@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.

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.

Thanks for the answer

Alex

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

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

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

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 = fread(fid);
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’);

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.

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.

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

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.

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

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.

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

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

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

@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.

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
linkaxes([ax1 ax2],'xy');
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

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
linkaxes([ax1 ax2],’xy’);
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);

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

@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.

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

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

@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. ;)

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?

@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');

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.

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.

@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.

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

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

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?

@Hannah,

In case you haven’t found this page in the documentation:

http://www.mathworks.com/help/techdoc/creating_plots/f7-21465.html

You can set default properties for pretty much everything regarding graphics (except for plot objects which are high-level objects). As you can see from the documentation, the default properties start with the word “Default” followed by the object type, followed by the object property. You can get the list of properties for various graphics objects here.

These postings are the author's and don't necessarily represent the opinions of MathWorks.