matlab example
Written by Daniel Herber on July 3, 2016.
This post provides a initial script that will allow for the customization of some of the most common elements of a high quality figure in MATLAB including the geometry, $\LaTeX$ labels, and the use of `export_fig`.
---
### Overview
Creating figures in MATLAB is quite easy but too often the defaults are utilized. There are some basic changes that can be made that give one better control over the final outputted image file. This post provides a short script that demonstrates these changes.
Not every figure will be the best displayed with the same options but understanding the capabilities of the MATLAB plotting engine will enable one to create the best figure for the situation. The scripts where written with the follow points in mind:
- Ability to change the basic geometric properties of the figure such as height, width, and axis limits.
- Easy addition of $\LaTeX$ labels, title, and legend.
- Change edge colors of the axes and legend from a dark grey to pure black.
- Export high quality image files of the figure with `export_fig` and `mfoldername` (see post [2016/01/04 - #3 - Using mfoldername with export_fig](http://www.danielherber.com/matlab.php?option=post_3)).
- Demonstrate some of the elements of the new MATLAB graphics system (since R2014b).
- Reasonably concise script.
- There are **two** examples, one with `surf` and another with `plot`.
---
### Example using Surf
This example uses the `peaks` function which creates a `surf` figure. Both the modified and original files are shown. The complete code follows the image files.
PDF output file with $\LaTeX$ and modifications:
PDF output file (original):
PNG output file with $\LaTeX$ and modifications:
[](blogs/matlab/post_5/peaks_latex.png){data-lightbox="blog_imgs" data-title="PNG output file with LaTeX and modifications"}
PNG output file (original):
[](blogs/matlab/post_5/peaks.png){data-lightbox="blog_imgs" data-title="PNG output file (original)"}
#### Code for Surf Example
```matlab
% data
[X,Y,Z] = peaks;
% data variables
xmin = -3;
xmax = 3;
ymin = -3;
ymax = 3;
zmin = -6.5466;
zmax = 8.0752;
myxlabel = '$x$'; % x label with latex
myylabel = '$y$'; % y label with latex
mylegend = ''; % legend with latex
mytitle = 'Peaks'; % title with latex
mysavename = 'peaks_latex'; % name to give the saved file
% plot variables
fwidth = 550; % figure width in pixels
fheight = 400; % figure height in pixels
fontlabel = 20; % x,y label font size
fontlegend = 12; % x,y legend font size
fonttick = 12; % x,y rick font size
mycolor1 = [0.8500 0.3250 0.0980]; % custom color 1
mycolor2 = [0.4940 0.1840 0.5560]; % custom color 2
wcolor = [1 1 1]; % white color
bcolor = [0 0 0]; % black color
%% pre tasks
set(0,'DefaultTextInterpreter','latex'); % change the text interpreter
set(0,'DefaultLegendInterpreter','latex'); % change the legend interpreter
set(0,'DefaultAxesTickLabelInterpreter','latex'); % change the tick interpreter
hf = figure; % create a new figure and save handle
hf.Color = wcolor; % change the figure background color
hf.Position = [200 200 fwidth fheight]; % set figure size and position
% add folder contents to the path
if exist('mfoldername', 'file') == 2 % check if it is in your path
pathfile = mfoldername(mfilename('fullpath'),''); % folder name for this file
addpath(genpath(pathfile)) % add contents
else
disp('mfoldername is not in your path')
disp('Available at https://www.mathworks.com/matlabcentral/fileexchange/40397')
end
%% plot the data
hp = surf(X,Y,Z);
axis('tight')
%% post tasks
xlabel(myxlabel) % create x label
ylabel(myylabel) % create y label
xlim([xmin xmax]) % change x limits
ylim([ymin ymax]) % change y limits
zlim([zmin zmax]) % change z limits
ha = gca; % get current axis handle
ha.XAxis.Color = bcolor; % change the x axis color to black (not a dark grey)
ha.YAxis.Color = bcolor; % change the y axis color to black (not a dark grey)
ha.ZAxis.Color = bcolor; % change the y axis color to black (not a dark grey)
ha.XAxis.FontSize = fonttick; % change x tick font size
ha.YAxis.FontSize = fonttick; % change y tick font size
ha.ZAxis.FontSize = fonttick; % change y tick font size
ha.XAxis.Label.FontSize = fontlabel; % change x label font size
ha.YAxis.Label.FontSize = fontlabel; % change y label font size
ha.ZAxis.Label.FontSize = fontlabel; % change y label font size
ha.Layer = 'top'; % place the axes on top of the data
% hl = legend(mylegend,'location','Best'); % create legend
% hl.FontSize = fontlegend; % change legend font size
% hl.EdgeColor = bcolor; % change the legend border to black (not a dark grey)
ht = title(mytitle);
ht.FontSize = fontlabel;
%% save the figure with export_fig
if exist('export_fig', 'file') == 2 % check if it is in your path
% save a png version
pathpng = mfoldername(mfilename('fullpath'),'png');
filename = [pathpng,mysavename];
str = ['export_fig ''',filename,''' -png'];
eval(str)
% save a pdf version
pathpdf = mfoldername(mfilename('fullpath'),'pdf');
filename = [pathpdf,mysavename];
str = ['export_fig ''',filename,''' -pdf'];
eval(str)
else
disp('export_fig is not in your path')
disp('Available at https://www.mathworks.com/matlabcentral/fileexchange/23629')
end
```
---
### Example using Plot
This example uses the basic `plot` function. Compared to the first example, this one better illustrates the geometric customization and a $\LaTeX$ legend. The PDF and PNG files are shown first and then the complete code.
PDF output file with $\LaTeX$ and modifications:
PNG output file with $\LaTeX$ and modifications:
[](blogs/matlab/post_5/plot_latex.png){data-lightbox="blog_imgs" data-title="PNG output file with LaTeX and modifications"}
#### Code for Plot Example
```matlab
% data
x = linspace(-2*pi,2*pi,50);
y = exp(-0.3*x).*sin(x);
% data variables
xmin = min(x); % x axis minimum
xmax = max(x); % x axis maximum
ymin = -2; % y axis minimum
ymax = 5; % y axis maximum
myxlabel = '$x$'; % x label with latex
myylabel = '$y$'; % y label with latex
mylegend = '$y = e^{-3x/10} \sin(x)$'; % legend with latex
mytitle = 'This is a Figure with \LaTeX'; % title with latex
mysavename = 'plot_latex'; % name to give the saved file
% plot variables
fwidth = 500; % figure width in pixels
fheight = 300; % figure height in pixels
fontlabel = 20; % x,y label font size
fontlegend = 12; % x,y legend font size
fonttick = 12; % x,y tick font size
mycolor1 = [0.8500 0.3250 0.0980]; % custom color 1
mycolor2 = [0.4940 0.1840 0.5560]; % custom color 2
wcolor = [1 1 1]; % white color
bcolor = [0 0 0]; % black color
%% pre tasks
set(0,'DefaultTextInterpreter','latex'); % change the text interpreter
set(0,'DefaultLegendInterpreter','latex'); % change the legend interpreter
set(0,'DefaultAxesTickLabelInterpreter','latex'); % change the tick interpreter
hf = figure; % create a new figure and save handle
hf.Color = wcolor; % change the figure background color
hf.Position = [200 200 fwidth fheight]; % set figure size and position
% add folder contents to the path
if exist('mfoldername', 'file') == 2 % check if it is in your path
pathfile = mfoldername(mfilename('fullpath'),''); % folder name for this file
addpath(genpath(pathfile)) % add contents
else
disp('mfoldername is not in your path')
disp('Available at https://www.mathworks.com/matlabcentral/fileexchange/40397')
end
%% plot the data
hp = plot(x,y,'.-','linewidth',2,'markersize',14,'color',mycolor1,...
'MarkerFaceColor',mycolor2,'MarkerEdgeColor',mycolor2); hold on
%% post tasks
xlabel(myxlabel) % create x label
ylabel(myylabel) % create y label
xlim([xmin xmax]) % change x limits
ylim([ymin ymax]) % change y limits
ha = gca; % get current axis handle
ha.XAxis.Color = bcolor; % change the x axis color to black (not a dark grey)
ha.YAxis.Color = bcolor; % change the y axis color to black (not a dark grey)
ha.XAxis.FontSize = fonttick; % change x tick font size
ha.YAxis.FontSize = fonttick; % change y tick font size
ha.XAxis.Label.FontSize = fontlabel; % change x label font size
ha.YAxis.Label.FontSize = fontlabel; % change y label font size
ha.Layer = 'top'; % place the axes on top of the data
hl = legend(mylegend,'location','Best'); % create legend
hl.FontSize = fontlegend; % change legend font size
hl.EdgeColor = bcolor; % change the legend border to black (not a dark grey)
ht = title(mytitle); % add the title
ht.FontSize = fontlabel; % set the title font size
%% save the figure with export_fig
if exist('export_fig', 'file') == 2 % check if it is in your path
% save a png version
pathpng = mfoldername(mfilename('fullpath'),'png');
filename = [pathpng,mysavename];
str = ['export_fig ''',filename,''' -png -m4'];
eval(str)
% save a pdf version
pathpdf = mfoldername(mfilename('fullpath'),'pdf');
filename = [pathpdf,mysavename];
str = ['export_fig ''',filename,''' -pdf'];
eval(str)
else
disp('export_fig is not in your path')
disp('Available at https://www.mathworks.com/matlabcentral/fileexchange/23629')
end
```