KAHIBARO Bookshelves
Discord Login Register

12. Advanced Plotting for Beginners

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

matlab
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

matlab
tiledlayout(2,3)

and then you create an individual axes with

matlab
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

matlab
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,

matlab
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

matlab
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

matlab
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.

Views: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Getting Started with MATLAB
    • ☰ 1.1. What Is MATLAB and What Is It Used For
      • ☰ 1.2. Installing MATLAB and Setting Up the Environment
        • ☰ 1.3. Understanding the MATLAB Desktop Interface
          • ☰ 1.4. Command Window, Workspace, and Current Folder
            • ☰ 1.5. Basic Workflow and Running Simple Commands
              • ☰ 1.6. Getting Help and Documentation
              • ☰ 2. MATLAB Language Basics
                • ☰ 2.1. MATLAB Syntax and Expressions
                  • ☰ 2.2. Variables and Assignment
                    • ☰ 2.3. Data Types and Type Conversion
                      • ☰ 2.4. Vectors and Matrices Fundamentals
                        • ☰ 2.5. Creating and Indexing Arrays
                          • ☰ 2.6. Basic Arithmetic and Elementwise Operations
                            • ☰ 2.7. Using Built-In Constants and Functions
                            • ☰ 3. Working with Variables and the Workspace
                              • ☰ 3.1. Creating, Viewing, and Editing Variables
                                • ☰ 3.2. Workspace Browser and Variable Inspector
                                  • ☰ 3.3. Saving and Loading Data Files
                                    • ☰ 3.4. MAT-Files and Importing External Data
                                      • ☰ 3.5. Clearing Variables and Managing the Workspace
                                      • ☰ 4. Vectors, Matrices, and Arrays
                                        • ☰ 4.1. Row and Column Vectors
                                          • ☰ 4.2. Matrix Creation and Concatenation
                                            • ☰ 4.3. Indexing, Slicing, and Logical Indexing
                                              • ☰ 4.4. Matrix Operations vs Elementwise Operations
                                                • ☰ 4.5. Reshaping and Rearranging Arrays
                                                  • ☰ 4.6. Special Matrices and Functions
                                                  • ☰ 5. Basic Programming Constructs
                                                    • ☰ 5.1. Scripts vs Functions
                                                      • ☰ 5.2. Control Flow with if, elseif, else
                                                        • ☰ 5.3. Loops with for and while
                                                          • ☰ 5.4. break, continue, and return
                                                            • ☰ 5.5. Logical Expressions and Relational Operators
                                                              • ☰ 5.6. Best Practices for Clear and Readable Code
                                                              • ☰ 6. Functions in MATLAB
                                                                • ☰ 6.1. Creating Simple Functions
                                                                  • ☰ 6.2. Function Inputs and Outputs
                                                                    • ☰ 6.3. Function Files and the Path
                                                                      • ☰ 6.4. Local vs Global Variables
                                                                        • ☰ 6.5. Anonymous Functions
                                                                          • ☰ 6.6. Organizing Code into Multiple Functions
                                                                          • ☰ 7. Working with Numbers and Math
                                                                            • ☰ 7.1. Scalars and Vectorized Computations
                                                                              • ☰ 7.2. Basic Mathematical Functions
                                                                                • ☰ 7.3. Trigonometric and Exponential Functions
                                                                                  • ☰ 7.4. Complex Numbers in MATLAB
                                                                                    • ☰ 7.5. Rounding, Modulo, and Special Values
                                                                                      • ☰ 7.6. Numerical Precision and Floating Point Considerations
                                                                                      • ☰ 8. Strings, Characters, and Categorical Data
                                                                                        • ☰ 8.1. Character Arrays and String Arrays
                                                                                          • ☰ 8.2. Creating and Manipulating Strings
                                                                                            • ☰ 8.3. Converting Between Data Types and Strings
                                                                                              • ☰ 8.4. Comparing and Searching Strings
                                                                                                • ☰ 8.5. Categorical Arrays Basics
                                                                                                • ☰ 9. Tables, Structures, and Cell Arrays
                                                                                                  • ☰ 9.1. Introduction to Tables
                                                                                                    • ☰ 9.2. Creating Tables and Accessing Data
                                                                                                      • ☰ 9.3. Modifying and Joining Tables
                                                                                                        • ☰ 9.4. Structures and Nested Structures
                                                                                                          • ☰ 9.5. Cell Arrays and Cell Indexing
                                                                                                            • ☰ 9.6. Choosing the Right Container Type
                                                                                                            • ☰ 10. Importing and Exporting Data
                                                                                                              • ☰ 10.1. Reading Text and CSV Files
                                                                                                                • ☰ 10.2. Importing Excel Spreadsheets
                                                                                                                  • ☰ 10.3. Importing Data with the Import Tool
                                                                                                                    • ☰ 10.4. Exporting Data to Files
                                                                                                                      • ☰ 10.5. Working with Image and Audio Files
                                                                                                                        • ☰ 10.6. Basic File Management from MATLAB
                                                                                                                        • ☰ 11. Plotting and Visualization
                                                                                                                          • ☰ 11.1. Introduction to 2D Plotting
                                                                                                                            • ☰ 11.2. Customizing Plots and Axes
                                                                                                                              • ☰ 11.3. Multiple Plots in One Figure
                                                                                                                                • ☰ 11.4. Labels, Titles, Legends, and Annotations
                                                                                                                                  • ☰ 11.5. Plotting with Different Line and Marker Styles
                                                                                                                                    • ☰ 11.6. Saving and Exporting Figures
                                                                                                                                    • ☰ 12. Advanced Plotting for Beginners
                                                                                                                                      • ☰ 12.1. Subplots and Tiled Layouts
                                                                                                                                        • ☰ 12.2. Bar, Scatter, and Stem Plots
                                                                                                                                          • ☰ 12.3. Histograms and Density Plots
                                                                                                                                            • ☰ 12.4. 3D Plots and Surface Plots
                                                                                                                                              • ☰ 12.5. Using plottools and Interactive Editing
                                                                                                                                                • ☰ 12.6. Basics of Handle Graphics
                                                                                                                                                • ☰ 13. Working with Scripts and Live Scripts
                                                                                                                                                  • ☰ 13.1. Creating and Running Script Files
                                                                                                                                                    • ☰ 13.2. Sectioning Code and Running Sections
                                                                                                                                                      • ☰ 13.3. Live Scripts and Rich Text
                                                                                                                                                        • ☰ 13.4. Adding Equations, Images, and Outputs
                                                                                                                                                          • ☰ 13.5. Sharing and Exporting Live Scripts
                                                                                                                                                          • ☰ 14. Debugging and Code Quality
                                                                                                                                                            • ☰ 14.1. Finding and Fixing Syntax Errors
                                                                                                                                                              • ☰ 14.2. Setting Breakpoints and Stepping Through Code
                                                                                                                                                                • ☰ 14.3. Inspecting Variable Values During Execution
                                                                                                                                                                  • ☰ 14.4. Using the Editor Debugging Tools
                                                                                                                                                                    • ☰ 14.5. Using Code Analyzer and Warnings
                                                                                                                                                                      • ☰ 14.6. Writing Clean and Maintainable MATLAB Code
                                                                                                                                                                      • ☰ 15. Basic Linear Algebra with MATLAB
                                                                                                                                                                        • ☰ 15.1. Vectors and Norms
                                                                                                                                                                          • ☰ 15.2. Matrix Addition and Multiplication
                                                                                                                                                                            • ☰ 15.3. Solving Linear Systems with Backslash
                                                                                                                                                                              • ☰ 15.4. Inverses, Determinants, and Rank
                                                                                                                                                                                • ☰ 15.5. Eigenvalues and Eigenvectors
                                                                                                                                                                                  • ☰ 15.6. Using Linear Algebra Functions Safely
                                                                                                                                                                                  • ☰ 16. Data Analysis and Statistics Fundamentals
                                                                                                                                                                                    • ☰ 16.1. Descriptive Statistics and Summary Measures
                                                                                                                                                                                      • ☰ 16.2. Sorting, Filtering, and Grouping Data
                                                                                                                                                                                        • ☰ 16.3. Basic Correlation and Regression
                                                                                                                                                                                          • ☰ 16.4. Simple Data Cleaning Techniques
                                                                                                                                                                                            • ☰ 16.5. Basic Time Series Handling
                                                                                                                                                                                            • ☰ 17. Working with Time and Dates
                                                                                                                                                                                              • ☰ 17.1. Representing Dates and Times
                                                                                                                                                                                                • ☰ 17.2. Creating and Formatting datetime Arrays
                                                                                                                                                                                                  • ☰ 17.3. Date Calculations and Differences
                                                                                                                                                                                                    • ☰ 17.4. Plotting Data over Time
                                                                                                                                                                                                    • ☰ 18. Introduction to Signal and Image Handling
                                                                                                                                                                                                      • ☰ 18.1. Basic Signal Representation in MATLAB
                                                                                                                                                                                                        • ☰ 18.2. Simple Filtering and Transformations
                                                                                                                                                                                                          • ☰ 18.3. Reading, Displaying, and Writing Images
                                                                                                                                                                                                            • ☰ 18.4. Basic Image Transformations
                                                                                                                                                                                                            • ☰ 19. Automation and Scripting Tasks
                                                                                                                                                                                                              • ☰ 19.1. Batch Processing of Files
                                                                                                                                                                                                                • ☰ 19.2. Writing Reusable Utility Scripts
                                                                                                                                                                                                                  • ☰ 19.3. Using Relative Paths and the MATLAB Path
                                                                                                                                                                                                                    • ☰ 19.4. Simple User Interaction with input and disp
                                                                                                                                                                                                                    • ☰ 20. Introduction to Toolboxes
                                                                                                                                                                                                                      • ☰ 20.1. What Are Toolboxes and How to Use Them
                                                                                                                                                                                                                        • ☰ 20.2. Exploring Installed Toolboxes
                                                                                                                                                                                                                          • ☰ 20.3. Finding Functions in Toolboxes
                                                                                                                                                                                                                            • ☰ 20.4. Add-Ons and MATLAB File Exchange
                                                                                                                                                                                                                            • ☰ 21. Best Practices and Next Steps
                                                                                                                                                                                                                              • ☰ 21.1. Organizing Projects and Folders
                                                                                                                                                                                                                                • ☰ 21.2. Version Control Basics with MATLAB
                                                                                                                                                                                                                                  • ☰ 21.3. Performance Tips for Beginners
                                                                                                                                                                                                                                    • ☰ 21.4. Learning Resources and Documentation Path
                                                                                                                                                                                                                                      • ☰ 21.5. Suggested Practice Projects for Beginners