Skip to content

MATLAB - Formatting a Plot

MATLAB’s default plots are functional, but for presentations, publications, or detailed analysis, you need to customize them. Effective formatting makes your data more understandable and highlights key insights. This involves adding descriptive labels, adjusting axes, changing colors, and annotating important features.

Modern MATLAB plotting is built on a system of graphics objects. Every element of a plot—the figure, the axes, the lines, the text—is an object with properties you can change. The most common workflow is:

  1. Create a plot.
  2. Get the handle to the graphics object you want to modify (e.g., the current axes).
  3. Change the properties of that object.

We will cover plot formatting in three main areas:

  • Labels and Annotations
  • Axes Appearance and Control
  • Colors and Colormaps

Labels provide context. A plot without a title or axis labels is often meaningless. Annotations, like text or arrows, draw attention to specific data points or regions.

The following functions are used to add labels and annotations. Most of them also accept optional name-value arguments to customize appearance.

FunctionDescription
title(txt)Adds a title to the current axes.
subtitle(txt)Adds a subtitle below the title.
xlabel(txt)Adds a label to the x-axis.
ylabel(txt)Adds a label to the y-axis.
zlabel(txt)Adds a label to the z-axis (for 3D plots).
legend()Creates a legend to identify multiple data series. Best used with the DisplayName property in plotting functions.
text(x, y, txt)Adds text to the plot at the specified data coordinates (x, y).
annotation(type, …)Adds shapes, arrows, or text boxes in coordinates relative to the figure, not the data.
xline(val)Creates a vertical line at a specific x-value.
yline(val)Creates a horizontal line at a specific y-value.

Let’s create a simple plot and add a title, subtitle, and axis labels. We can customize the font size and color directly in the function call using name-value pairs.

% 1. Define data
x = 0:0.1:2*pi;
y = sin(x);
% 2. Create the plot
plot(x, y, 'LineWidth', 2);
% 3. Add labels and title
title('Sine Wave Analysis', 'Color', 'b', 'FontSize', 16);
subtitle('From 0 to 2*pi');
xlabel('Angle [rad]');
ylabel('Amplitude');
grid on; % Add a grid for better readability

Expected Output: A plot of a sine wave is displayed. It has a main title ‘Sine Wave Analysis’ in a blue, 16-point font. Below it, a smaller subtitle reads ‘From 0 to 2*pi’. The x-axis is labeled ‘Angle [rad]’ and the y-axis is ‘Amplitude’. A grid is visible in the background.

Example 2: Adding a Legend and Annotations

Section titled “Example 2: Adding a Legend and Annotations”

The modern and most robust way to create a legend is to specify the DisplayName for each line when you plot it. MATLAB will then automatically use these names in the legend.

x = linspace(0, 10, 150);
y1 = cos(x);
y2 = 0.5 * cos(x - 0.5);
% Plot data series with 'DisplayName' for the legend
figure; % Create a new figure window
hold on; % Allow multiple plots on the same axes
plot(x, y1, 'DisplayName', 'Signal A', 'LineWidth', 2);
plot(x, y2, 'DisplayName', 'Signal B (shifted)', 'LineWidth', 2);
hold off;
% Add a legend using the specified display names
legend('Location', 'northeast');
title('Comparison of Two Signals');
xlabel('Time (s)');
ylabel('Value');
% Annotate a peak
text(0.5, 1, ' Initial Peak', 'FontWeight', 'bold');
% Add a vertical line to mark an event
xline(5, '--r', 'Event X');

Expected Output: The plot shows two cosine waves. A legend in the top-right corner correctly labels the solid line as ‘Signal A’ and the dashed line as ‘Signal B (shifted)’. The text ‘Initial Peak’ appears near the first peak of Signal A. A vertical dashed red line is drawn at x=5 with the label ‘Event X’.

You have full control over the axes, including their limits, scale (linear or logarithmic), ticks, and surrounding box. The best practice is to get the handle to the current axes using ax = gca; and then modify its properties.

Property/FunctionDescription
xlim, ylim, zlimSets or gets the limits for the corresponding axis. Example: xlim([0 10]).
ax.XScale, ax.YScaleSets the axis scale to ‘linear’ or ‘log’. Example: ax.XScale = 'log';.
ax.XTick, ax.YTickSpecifies the locations of tick marks. Example: ax.XTick = 0:pi:2*pi;.
ax.XTickLabel, ax.YTickLabelProvides custom text labels for each tick mark. Example: ax.XTickLabel = {'0', '\pi', '2\pi'};.
box on/offToggles the visibility of the box outline around the plot.
grid on/off/minorToggles the visibility of the major and minor grid lines.
axis equal/tightAdjusts aspect ratio or fits the axes tightly around the data.

This example demonstrates how to control various axes properties for a publication-quality plot.

x = logspace(-1, 2, 100); % Creates logarithmically spaced vector
y = 1 ./ (1 + x);
plot(x, y, 'LineWidth', 2);
title('Frequency Response');
xlabel('Frequency (Hz)');
ylabel('Gain');
% Get the current axes handle
ax = gca;
% Set axis properties
ax.XScale = 'log'; % Use a logarithmic x-axis
ax.XLim = [0.1 100]; % Set x-axis limits
ax.YLim = [0 1.1]; % Set y-axis limits
ax.FontSize = 12; % Set font size for the whole axes
ax.XGrid = 'on'; % Turn on grid for x-axis only
ax.YGrid = 'on'; % Turn on grid for y-axis only
ax.GridAlpha = 0.5; % Make grid lines semi-transparent
ax.Box = 'on'; % Ensure the box outline is visible

Expected Output: A plot showing gain versus frequency is displayed. The x-axis has a logarithmic scale, ranging from 0.1 to 100. The y-axis is linear, from 0 to 1.1. The plot is enclosed in a box with semi-transparent grid lines, and all text has a font size of 12.

Color is a powerful tool for distinguishing data or representing a third dimension on a 2D plot (e.g., heatmaps). MATLAB provides a set of built-in colormaps, with parula being the default. parula and other modern colormaps like viridis and plasma are designed to be visually uniform and clear to viewers with color-vision deficiencies.

FunctionDescription
colormap(map)Applies a specified colormap to the current figure. map can be a predefined name (e.g., ‘viridis’) or a custom M-by-3 array of RGB values.
colorbarDisplays a color bar that shows the mapping of colors to data values.
clim([cmin cmax])Controls the color limits, mapping cmin to the first color and cmax to the last color in the colormap.

Surface plots are a common use case for colormaps. Here, we’ll visualize the peaks function and customize its color representation.

% 1. Generate surface data
[X, Y, Z] = peaks(25);
% 2. Create the surface plot
figure;
surf(X, Y, Z);
% 3. Apply a modern, accessible colormap
colormap(viridis);
% 4. Add a colorbar with a descriptive label
cb = colorbar;
cb.Label.String = 'Elevation';
% 5. Adjust color limits to focus on a specific range
% clim([-5 5]);
title('Surface Plot with Viridis Colormap');
xlabel('X-coordinate');
ylabel('Y-coordinate');
zlabel('Z-coordinate');

Expected Output: A 3D surface plot of the peaks function is generated. The surface is colored using the ‘viridis’ colormap, which transitions from deep blue through green to bright yellow. To the right of the plot, a vertical color bar is displayed, showing the color scale and labeled ‘Elevation’.