Table of Contents
Adjusting Figure and Axes after a Basic Plot
Once you create a simple plot with a command like plot(x, y), MATLAB automatically creates a figure window and an axes object. You can then customize almost every visual aspect of that plot. In this chapter you will focus on changing the appearance of the existing figure and axes, not on how to create different plot types, and not on how to add labels or legends, which are covered elsewhere.
A typical starting point is something like:
x = 0:0.1:2*pi;
y = sin(x);
plot(x, y);From this point you can modify the figure and axes using additional commands.
Basic Line and Color Customization
The quickest customizations are applied directly in the plot command. MATLAB lets you set line style, marker, and color using short codes. For example:
plot(x, y, 'r--'); % red dashed line
plot(x, y, 'bo'); % blue circle markers, no line
plot(x, y, 'k-.*'); % black solid line with star markers
The format string 'r--' is interpreted as a color code combined with a line style. Common color codes are 'r' for red, 'g' for green, 'b' for blue, 'k' for black, and 'm' for magenta. Common line styles are '-' for solid and '--' for dashed.
You can also set properties in name-value form. This is more verbose but very clear:
plot(x, y, 'Color', [0.2 0.6 0.8], ...
'LineStyle', '--', ...
'LineWidth', 2, ...
'Marker', 'o', ...
'MarkerSize', 8);
Here the color is specified as an RGB triplet. Each component is between 0 and 1, where [0 0 0] is black and [1 1 1] is white.
If you do not want points connected with a line, you can set the line style to 'none' and use markers only:
plot(x, y, 'LineStyle', 'none', 'Marker', 'x');Getting Handles for Later Customization
For more control it is useful to capture the output of plotting commands. Most graphics functions return a handle, which is an object you can modify after the plot is drawn:
h = plot(x, y);Now you can change properties later:
h.LineWidth = 3;
h.Color = [0 0.5 0];
h.Marker = 's';
h.MarkerFaceColor = 'y';Changing these properties updates the plot immediately in the figure.
You can also get handles to the current axes and figure with:
ax = gca; % get current axes
fig = gcf; % get current figureThese objects control the appearance of the axes frame, ticks, background, and the figure window itself.
Controlling Axes Limits
By default MATLAB picks data limits for the x and y axes based on the plotted data. You can override these limits using xlim and ylim:
xlim([0 2*pi]);
ylim([-1.5 1.5]);
Each function accepts a two element vector [min max]. MATLAB will then fix the view to that range, even if new data is added outside it.
You can also query the current limits:
xl = xlim; % returns something like [0 6.2832]
yl = ylim;The same properties are available through the axes handle:
ax = gca;
ax.XLim = [0 2*pi];
ax.YLim = [-2 2];
To ensure both axes use the same scaling you can use the axis equal command:
axis equal;This is especially useful for plots where geometric shapes should not appear stretched.
The axis function can also set limits directly:
axis([xmin xmax ymin ymax]);For example:
axis([0 10 -5 5]);Adjusting Axis Ticks and Tick Labels
Axes ticks mark specific numeric positions along each axis. MATLAB chooses them automatically, but you can change both the locations and the labels.
To specify exact tick positions:
ax = gca;
ax.XTick = 0:0.5:2*pi;
ax.YTick = -1:0.5:1;This sets the x ticks from 0 to $2\pi$ in steps of 0.5, and the y ticks from -1 to 1 in steps of 0.5.
Often the positions are fine but the default numeric labels are not. You can set custom text labels that correspond to the tick positions:
ax.XTick = [0 pi/2 pi 3*pi/2 2*pi];
ax.XTickLabel = {'0','\pi/2','\pi','3\pi/2','2\pi'};
Now the x axis shows symbolic looking labels instead of numeric ones. The number of elements in XTickLabel must match the number of entries in XTick.
To remove tick labels, you can clear them:
ax.XTickLabel = [];
ax.YTickLabel = [];To remove ticks entirely you can set:
ax.XTick = [];
ax.YTick = [];Grid Lines and Minor Ticks
Grid lines help read values from the plot. You can enable a grid on the current axes with:
grid on;or turn it off with:
grid off;
The command grid minor shows additional minor grid lines between major ticks, if minor ticks are enabled.
You can control the grid appearance through axes properties:
ax = gca;
ax.XGrid = 'on';
ax.YGrid = 'on';
ax.GridLineStyle = '--';
ax.GridColor = [0.8 0.8 0.8];
ax.GridAlpha = 0.5; % transparency between 0 and 1Similarly, minor grids use:
ax.XMinorGrid = 'on';
ax.YMinorGrid = 'on';Minor ticks can be turned on without grid lines:
ax.XMinorTick = 'on';
ax.YMinorTick = 'on';This adds additional tick marks between the major ticks, which can make detailed plots easier to read.
Changing Line Styles and Families of Curves
When you have multiple lines on the same axes, you may want to distinguish them clearly through line width, style, markers, and color.
A common pattern is:
plot(x, sin(x), 'b-', ...
x, cos(x), 'r--', ...
x, 0.5*sin(2*x), 'k:');This plots three lines with different style strings.
If you call plot several times in a row, the hold on command is useful. It keeps the existing content, so you can add more plots without clearing the axes:
plot(x, sin(x), 'LineWidth', 2);
hold on;
plot(x, cos(x), 'LineWidth', 2, 'LineStyle', '--');
hold off;With this approach you can store each line handle and customize them separately:
plot(x, sin(x));
hold on;
h2 = plot(x, cos(x));
hold off;
h2.Color = [1 0 0];
h2.LineStyle = ':';
h2.LineWidth = 1.5;Axes Appearance, Box, and Background
The axes frame and background contribute to the readability and style of the plot. You can control whether a box is drawn around the axes:
box on;
box off;
Some styles prefer a top and right border removed, which is what box off does.
The background color of the axes can be changed using:
ax = gca;
ax.Color = [0.95 0.95 0.95]; % light gray backgroundIf you want a transparent background that shows the figure color, you can set:
ax.Color = 'none';The figure itself has its own background color:
fig = gcf;
fig.Color = 'w'; % white figure backgroundThis is useful when preparing plots for documents with white pages.
You can also control the axis location and visibility. For example:
ax.XAxisLocation = 'origin'; % x axis through y = 0
ax.YAxisLocation = 'origin'; % y axis through x = 0or hide axes ticks and labels entirely for a clean look:
ax.Visible = 'off';Linear, Logarithmic, and Other Scales
Sometimes the scale of the data makes a linear axis inappropriate. MATLAB lets you switch to logarithmic scales on each axis independently.
For a logarithmic x axis:
set(gca, 'XScale', 'log');For a logarithmic y axis:
set(gca, 'YScale', 'log');You can combine both:
set(gca, 'XScale', 'log', 'YScale', 'log');
You can also use specialized plotting functions like semilogx, semilogy, and loglog, but changing XScale and YScale works on existing plots without recreating them.
Be aware that logarithmic scales cannot display zero or negative values. If your data includes such values they will not appear and MATLAB will often warn you.
Aspect Ratio and Plot Box Adjustment
The relationship between the units on the x and y axes affects how shapes appear. To make one unit on the x axis equal the same physical length as one unit on the y axis, use:
axis equal;To preserve the data aspect ratio but let MATLAB adjust limits automatically, use:
axis image;
There is also an axis tight option which shrinks the axes limits to fit the data closely:
axis tight;
and an axis padded option which adds a little extra space around the data:
axis padded;You can control the aspect ratios more explicitly using axes properties:
ax = gca;
ax.DataAspectRatio = [1 1 1];
ax.PlotBoxAspectRatio = [4 3 1];These properties are typically used when the exact relative scaling matters, for example in maps or geometry plots.
Multiple Axes in the Same Figure
Sometimes you want two different x or y scales on the same figure. One way to do this is to create a second axes that overlap, or to use yyaxis for two y axes.
The command yyaxis creates a left and a right y axis in the same axes area:
x = 0:0.1:10;
y1 = sin(x);
y2 = 100*cos(x);
yyaxis left
plot(x, y1, 'b-');
yyaxis right
plot(x, y2, 'r--');Each side has its own ticks and limits, but shares the same x axis.
Axes overlapping and more complex layouts are covered in dedicated chapters. Here the focus is that MATLAB lets you have more than one axis scale within one visual figure, which is often useful for comparing related quantities with different units.
Controlling Fonts and Text Appearance on Axes
While labels and titles themselves are discussed elsewhere, the visual properties of text on the axes are an important part of customizing a plot. The axes object controls the font for tick labels and other default text.
You can change the font name, size, and weight:
ax = gca;
ax.FontName = 'Helvetica';
ax.FontSize = 12;
ax.FontWeight = 'bold';
These properties affect the tick labels and axis labels that use default settings. Titles and labels created with title, xlabel, and ylabel can override these properties individually, but often inheriting from the axes is sufficient.
If you need different fonts on different axes within the same figure, you can set FontName and related properties separately for each axes handle.
Colormaps and Lines in Multi-line Plots
When you plot multiple lines in a single call, MATLAB cycles through colors based on the current colormap and color order. You can adjust the color order if you want a specific sequence:
ax = gca;
ax.ColorOrder = [ ...
0 0.4470 0.7410; % blue
0.8500 0.3250 0.0980; % orange
0.9290 0.6940 0.1250]; % yellowThen calling:
plot(x, sin(x), x, cos(x), x, sin(2*x));uses these three colors in order, then repeats them if there are more lines.
Colormaps are more critical for images and surfaces, but they also affect some line plotting styles and legends. You can set a global colormap for a figure using:
colormap(parula); % default MATLAB colormap
colormap(jet); % high contrast colormapRemember that colormaps are applied mostly to objects that use color to represent data values, such as images and surfaces, which are covered in other chapters.
Saving Customized Settings for Reuse
If you find yourself frequently applying the same set of customizations, you can write a small script or function that accepts an axes handle and applies preferred settings. For example:
function prettifyAxes(ax)
if nargin < 1
ax = gca;
end
ax.FontName = 'Helvetica';
ax.FontSize = 12;
ax.LineWidth = 1;
ax.Box = 'on';
ax.XGrid = 'on';
ax.YGrid = 'on';
ax.GridColor = [0.8 0.8 0.8];
ax.GridAlpha = 0.4;
endThen after any plot you can call:
prettifyAxes(gca);This ensures you get a consistent style across your figures without repeating many lines of customization code.
Important points to remember:
- Use handles to lines, axes, and figures to change plot properties after plotting.
- Control axes limits with
xlim,ylim, andaxis, and adjust tick locations and labels throughXTick,YTick, and theirLabelcounterparts. - Use
grid on, minor ticks, and line styles to improve readability, not just aesthetics. - Adjust scales using
XScaleandYScalefor linear or logarithmic axes, and useaxis equalwhen geometry should not look stretched. - Set fonts and background colors on the axes and figure to match the intended output medium, such as screens or printed pages.