MATLAB - Formatting a Plot
MATLAB - Formatting Plots
Section titled “MATLAB - Formatting Plots”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:
- Create a plot.
- Get the handle to the graphics object you want to modify (e.g., the current axes).
- 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 and Annotations
Section titled “Labels and Annotations”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.
Functions for Labels and Annotations
Section titled “Functions for Labels and Annotations”| Function | Description |
|---|---|
| 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. |
Example 1: Basic Labels and Title
Section titled “Example 1: Basic Labels and Title”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 datax = 0:0.1:2*pi;y = sin(x);
% 2. Create the plotplot(x, y, 'LineWidth', 2);
% 3. Add labels and titletitle('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 readabilityExpected 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 legendfigure; % Create a new figure windowhold on; % Allow multiple plots on the same axesplot(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 nameslegend('Location', 'northeast');
title('Comparison of Two Signals');xlabel('Time (s)');ylabel('Value');
% Annotate a peaktext(0.5, 1, ' Initial Peak', 'FontWeight', 'bold');
% Add a vertical line to mark an eventxline(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’.
Axes Appearance and Control
Section titled “Axes Appearance and Control”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/Function | Description |
|---|---|
| xlim, ylim, zlim | Sets or gets the limits for the corresponding axis. Example: xlim([0 10]). |
| ax.XScale, ax.YScale | Sets the axis scale to ‘linear’ or ‘log’. Example: ax.XScale = 'log';. |
| ax.XTick, ax.YTick | Specifies the locations of tick marks. Example: ax.XTick = 0:pi:2*pi;. |
| ax.XTickLabel, ax.YTickLabel | Provides custom text labels for each tick mark. Example: ax.XTickLabel = {'0', '\pi', '2\pi'};. |
| box on/off | Toggles the visibility of the box outline around the plot. |
| grid on/off/minor | Toggles the visibility of the major and minor grid lines. |
| axis equal/tight | Adjusts aspect ratio or fits the axes tightly around the data. |
Example 3: Customizing Axes
Section titled “Example 3: Customizing Axes”This example demonstrates how to control various axes properties for a publication-quality plot.
x = logspace(-1, 2, 100); % Creates logarithmically spaced vectory = 1 ./ (1 + x);
plot(x, y, 'LineWidth', 2);
title('Frequency Response');xlabel('Frequency (Hz)');ylabel('Gain');
% Get the current axes handleax = gca;
% Set axis propertiesax.XScale = 'log'; % Use a logarithmic x-axisax.XLim = [0.1 100]; % Set x-axis limitsax.YLim = [0 1.1]; % Set y-axis limitsax.FontSize = 12; % Set font size for the whole axesax.XGrid = 'on'; % Turn on grid for x-axis onlyax.YGrid = 'on'; % Turn on grid for y-axis onlyax.GridAlpha = 0.5; % Make grid lines semi-transparentax.Box = 'on'; % Ensure the box outline is visibleExpected 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.
Colors and Colormaps
Section titled “Colors and Colormaps”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.
| Function | Description |
|---|---|
| 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. |
| colorbar | Displays 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. |
Example 4: Using Colormaps and a Colorbar
Section titled “Example 4: Using Colormaps and a Colorbar”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 plotfigure;surf(X, Y, Z);
% 3. Apply a modern, accessible colormapcolormap(viridis);
% 4. Add a colorbar with a descriptive labelcb = 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’.