Table of Contents
Overview
In this chapter you move a step beyond basic 2D plotting and explore a set of tools that give you much more control and flexibility when you visualize data in MATLAB. The focus is on techniques that are still suitable for beginners, but that already feel more “advanced” than a single simple plot call.
You will learn how to arrange multiple plots in one figure window, how to use different plot types for different kinds of data, and how to start working with 3D visualizations. You will also see how to use interactive plot tools and how MATLAB represents graphics objects internally through “handles.” All of these topics build on basic plotting concepts, but open the door to more professional looking figures and more efficient data exploration.
Multiple Plots in a Single Window
A single figure window can show more than one axes region. This is useful when you want to compare several related plots, show different views of the same data, or keep raw data and processed data side by side.
The classic way to create a grid of axes is the subplot function. It divides the figure into a regular grid of rows and columns and activates one cell at a time. The basic calling form is
$$
\texttt{subplot}(m, n, p)
$$
where m is the number of rows, n the number of columns, and p the index of the active position, counted row by row. For example, the call
subplot(2,2,3)
creates or activates the third axes in a 2 by 2 layout. After you call subplot, any normal plotting command, such as plot, bar, or scatter, will draw into that active axes.
You can build up a figure with several plots by calling subplot followed by a plotting command for each panel. If you call subplot with the same m, n, p values again, MATLAB reuses that axes instead of creating a new one. This is useful when you want to update or overwrite a particular panel during a loop or after changing the data.
Although subplot is simple, it has some limitations, for example relatively coarse control of spacing and titles that are specific to individual axes. For more control, MATLAB provides the tiledlayout system, which separates the layout into two steps. First you define the overall grid with a call such as
tiledlayout(2,3)and then you create an individual axes with
nexttile
for each panel. Each call to nexttile returns an axes object that you can store in a variable. This allows you to modify a particular axes later, for example to change its limits or labels, or to share a colorbar across multiple panels.
A key difference is that tiledlayout handles spacing, padding, and common titles more gracefully. It also gives you more options via name value pairs such as TileSpacing and Padding. Because you can keep references to the axes that nexttile creates, it is easier to write scripts that adjust layouts in a programmatic way.
Flexible Layouts with Tiled Layouts
A tiled layout is particularly suitable when you need clean, publication style figures. Instead of using a single index like subplot(2,2,1), you treat the layout as an object that manages all tiles.
When you call
tl = tiledlayout(2,2);
you store the layout object in tl. Each subsequent call to nexttile creates a new axes in the next tile. You can pass an index to nexttile too, for example nexttile(4) activates the fourth tile, similar to subplot. This is useful when you want to fill tiles in a specific order.
Tiled layouts make it easy to add a title for the whole figure using title on the layout object rather than on individual axes. For example,
title(tl,'Overall Experiment Results')adds a single title centered above all tiles. This is different from setting the title of a particular axes, which only labels one panel.
Another advantage of tiledlayout is that tiles can span multiple grid positions. For example, you can have one wide plot on top and two smaller plots below it. To do this you can call nexttile with span arguments that specify how many rows and columns the axes should cover. This kind of flexible layout is hard to achieve with the classic subplot interface.
By carefully choosing the grid size and how tiles span the grid, you can create sophisticated layouts such as one large overview plot accompanied by several smaller detail plots. Tiled layouts are designed to keep spacing and alignment consistent, which improves readability and reduces the need for manual tweaking.
Bar, Scatter, and Stem Plots
Not all data is best represented with simple lines. MATLAB offers several specialized plot types suited to different kinds of measurements and categories. For discrete categories with associated values, bar charts are common. For point clouds and paired observations without an obvious continuous curve, scatter plots are often more meaningful. For data measured at discrete positions along an axis, stem plots can visually emphasize each sample.
A bar plot uses rectangles whose heights represent values. You typically use this when you have relatively few categories or bins. The basic function is bar. You can pass a vector of values and MATLAB will position bars at consecutive x positions. If you pass two matrices of compatible sizes, MATLAB can create grouped or stacked bars. Options such as specifying the bar width or orientation help adjust the appearance. Because bar charts emphasize magnitude comparisons, they are a natural choice for summary statistics, counts, or averages across groups.
Scatter plots focus on the positions of individual points specified by their x and y coordinates. You call scatter with at least two vectors, one for x and one for y. A scatter plot is particularly useful when you want to see patterns such as clusters or correlations in your data rather than a connected line. You can also vary the marker size and color by passing additional arguments. This allows you to visualize a third or fourth variable, for example value by marker size and category by marker color.
Stem plots combine aspects of line plots and discrete markers. The function stem draws a vertical or horizontal line from a baseline to each data point, with a marker at the top. This style makes it clear that the data is sampled at specific discrete points rather than continuous. It is frequently used in introductory signal processing tasks, for example to display a small number of samples of a waveform or impulse responses.
All of these plot types integrate into multiple axes layouts in the same way as plot. After you have an axes selected by subplot or nexttile, calling bar, scatter, or stem directs their output to that axes. By mixing different plot types in different panels, you can represent both raw data and derived summaries within one figure.
Working with Histograms and Density Plots
Histograms help you understand how values in a data set are distributed. Instead of showing each individual observation, they group values into bins and display how many fall into each bin. MATLAB creates histograms using the histogram function. When you pass a vector of data, MATLAB automatically chooses bin edges by default, but you can control the number and location of bins with additional arguments.
The height of each bar in a histogram indicates frequency or count by default. You can change the normalization so that the total area sums to 1, which creates a view closer to a probability density. This can be important when you want to compare distributions from data sets of different sizes. Histogram objects also allow interactive adjustments, for example using the property inspector or through code that modifies properties such as BinWidth.
Closely related to histograms are density style plots. Instead of discrete bars, these approximate the underlying probability density function. In MATLAB this can be achieved using functions that estimate kernel density and then plotting the result with plot. Although the detailed methods for density estimation belong to data analysis topics, at the plotting level the idea is that you use continuous curves instead of or alongside histograms to compare distributions.
You can combine histograms with other plots within the same figure. For instance, you might place a histogram in one tile to show the distribution of errors and a line plot in another tile to show how those errors change over time. You can also overlay a theoretical density curve on top of a histogram by calling hold on before plotting the curve. When you do this, it is important to match the axis scales and normalization so that the comparison is meaningful.
Histograms also work for categorical data when you convert categories to numeric codes or use specialized plotting functions that understand categorical types. This becomes relevant when you move to tables and mixed data, because you often want to see how values are distributed across categories rather than only as raw numbers.
Introduction to 3D and Surface Plots
While most introductory plots are two dimensional, MATLAB provides simple ways to visualize data that depends on two independent variables, for example height as a function of x and y. The resulting visualization is naturally three dimensional. The most common basic 3D plot types are line plots in 3D space and surface or mesh plots over a grid.
A 3D line plot uses the function plot3. You pass three vectors of equal length representing x, y, and z coordinates, and MATLAB draws a curve in 3D space. This is useful for trajectories or paths where you track position in three coordinates, for example a particle moving through space or parameterized curves.
Surface plots visualize a function of two variables, often represented as a matrix. If you think of x and y forming a rectangular grid, then the corresponding z values form a matrix where each element is the function value at a specific grid point. To create such grids you typically use helper functions that generate coordinate matrices. Once you have x, y, and z shaped appropriately, you can call surf to create a colored surface, or mesh to create a wireframe style plot. MATLAB maps z values or another quantity to colors on the surface, which can reveal peaks, valleys, and gradients.
Working with 3D plots introduces additional viewing controls that are not relevant in pure 2D. The 3D axes have a camera position and target that determine how the scene is projected onto your screen. In practice you usually adjust the view interactively with the rotation tool, but you can also set the view angle and azimuth numerically for reproducible figures. The axes object in 3D also has properties like DataAspectRatio that control how scales on the three axes relate to each other, which affects how shapes appear.
You can place 3D plots inside tiled layouts just as you do for 2D axes. This is useful if you want to show a surface plot in one tile and corresponding contour lines in another, or if you want to compare several parameter settings. However, you should keep in mind that 3D plots are more visually dense, so giving them enough space within the layout often improves readability.
Interactive Plot Tools
MATLAB includes interactive tools that allow you to explore and modify plots using the mouse instead of writing code for every change. These tools are particularly useful when you want to quickly inspect data, adjust labels, or export a figure with small cosmetic changes.
When a figure window is active, the figure toolbar includes tools for zooming, panning, rotating 3D views, and data cursor inspection. The zoom and pan tools let you focus on particular regions of a plot. For 3D plots there is a rotate tool that lets you drag to change the view. These interactions do not change your underlying data, only how it is displayed.
The data cursor tool lets you click on a plotted point to see its coordinates and the corresponding value. This is a convenient way to read off specific values without writing custom code. You can also add multiple data tips and compare different locations in the data. Behind the scenes, these interactive annotations are part of the graphics object tree that MATLAB uses to represent everything in the figure.
Interactive editing tools let you modify plot elements such as line styles, colors, markers, and text labels. You can usually double click on an element or right click to access context menus. Changes you make are reflected immediately in the figure. For quick exploratory tasks or when you are still deciding about the best way to present your data, this can be much faster than going back to the script each time.
Although these tools are convenient, they do not automatically update your code. If you need reproducible figures, it is important to transfer any edits you like into your scripts. As you become more comfortable with plotting functions and graphics handles, you will tend to rely more on code and use the interactive tools primarily to discover settings that you then translate into scripting form.
Basics of Handle Graphics
Every visible element in a MATLAB figure is an object, and each object has a numeric or object handle. When you create a plot, MATLAB returns handles that you can store. For example, a call like
h = plot(x,y);
assigns the handle of the line object to h. You can then use h to modify properties of that line, such as color, line width, or marker style, without redrawing the plot. This approach is known as handle graphics.
Handles create a connection between plotting commands and properties. Instead of repeating a plot with different style arguments, you can plot once, store the handle, and change its properties in several steps. For instance, you can write
h.LineWidth = 2;
h.Color = [0 0.5 0];to adjust the appearance. The exact list of properties depends on the type of object. Lines, surfaces, axes, and figures each have their own sets of customizable properties.
Figures themselves are handle objects, as are axes. When you create a new figure using figure, MATLAB returns a figure handle. You can use this handle to modify the figure properties or to select it as the current target for plotting. Similarly, calls that create axes, such as subplot or nexttile, return axes handles. You can use these to control axis limits, labels, and other decorations via properties.
Objects are organized in a parent child hierarchy. For instance, a line has an axes as its parent, and an axes has a figure as its parent. Understanding this hierarchy is helpful when you want to apply changes that affect groups of objects. For example, changing a property on an axes, such as the colormap or font size, will affect all plots that live inside that axes.
Handle graphics also come into play when you work with interactive tools or build more advanced user interfaces in MATLAB. Even at a beginner level, becoming comfortable with storing and using handles lets you write clearer plotting code and avoid accidental overwriting of figures. Instead of relying on the current axes or current figure, you can explicitly reference exactly the object you want to modify.
Key ideas to remember: use subplot or tiledlayout with nexttile to organize multiple plots in one figure, choose appropriate plot types such as bar, scatter, stem, histogram, and 3D surfaces for your data, use interactive plotting tools for quick exploration, and store and use handles for precise control of graphics objects and their properties.