11.3. Multiple Plots in One Figure
Table of Contents
Why Use Multiple Plots in One Figure
In many situations you want to compare several data sets that share the same x values, or you want to show related information together. MATLAB makes it straightforward to place multiple plots into a single figure. You can do this either by drawing several lines on one set of axes, or by combining separate axes inside the same figure. This chapter focuses on plotting multiple data series in one axes and creating additional axes in a controlled way, without going into layout systems that are covered elsewhere.
Plotting Multiple Lines in the Same Axes
The most direct way to show several data sets together is to call plot with multiple pairs of x and y values. MATLAB draws each pair as a separate line on the same axes.
For example, suppose you have a common x vector and three different y vectors.
x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);
y3 = sin(2*x);
plot(x, y1, x, y2, x, y3);
In this single call to plot, MATLAB overlays three lines in one axes. The first pair x, y1 creates the first line, the second pair x, y2 creates the second, and so on. MATLAB automatically uses different colors in the default color order for each line.
You are not limited to two arguments. Any even number of arguments, interpreted as (x1, y1, x2, y2, x3, y3, ...), will produce that many lines in the same axes.
Holding the Current Plot with `hold on` and `hold off`
Sometimes you want more control and prefer to build the figure step by step. The hold command lets you add new plots to the existing axes without erasing what is already drawn.
By default, a new plot call clears the axes and replaces the existing content. To prevent this, use hold on.
x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);
plot(x, y1); % First line
hold on; % Keep existing plot
plot(x, y2); % Second line, added to the same axes
hold off; % Return to default behavior
When hold on is active, new graphics objects are added. When you call hold off, MATLAB restores the original behavior where new plotting commands clear the axes before drawing.
You can also call hold with no arguments to toggle the state.
plot(x, y1);
hold; % Toggle: if it was off it turns on, if on it turns off
plot(x, y2); % May or may not overlay depending on state
It is usually clearer to use hold on and hold off explicitly so that anyone reading your code can see the intended behavior.
Combining Different Plotting Functions in One Axes
hold on allows you to mix different plotting functions in the same axes. For instance, you might want to draw a line and then highlight specific points using markers from another function.
x = 0:0.1:2*pi;
y = sin(x);
plot(x, y); % Continuous line
hold on;
plot(x(1:5:end), y(1:5:end), 'ro'); % Red circles at every 5th point
hold off;
Here the first plot call creates the main curve. With hold on active, the second plot adds red circle markers at selected x values. You could similarly combine line plots with stem plots or area plots, as long as you apply hold on before the second command.
You can also mix plot with other graphics functions, for example yline or xline to show reference lines together with your data.
x = 0:0.1:10;
y = exp(-0.3*x).*sin(2*x);
plot(x, y);
hold on;
yline(0, '--k'); % Horizontal line at y = 0
hold off;Controlling Colors and Styles for Multiple Plots
When you create several lines in one axes, MATLAB assigns colors from its default color order. To distinguish lines clearly, you often want to choose colors and styles yourself.
You can specify line style and color as an additional argument in each plot call. For example:
x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);
plot(x, y1, 'r-'); % Red solid line
hold on;
plot(x, y2, 'b--'); % Blue dashed line
hold off;
The style string 'r-' means red solid line, while 'b--' means blue dashed line. You can also include markers, such as 'g:o' for a green dotted line with circle markers.
If you use one plot call with multiple (x, y) pairs, you can still control each line style individually by inserting style strings between the pairs.
x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);
y3 = sin(2*x);
plot(x, y1, 'r-', x, y2, 'b--', x, y3, 'k:');In this example, the first line is red and solid, the second blue and dashed, and the third black and dotted. This method keeps all lines in a single call while giving you clear visual differences.
Plotting Against a Common x Without Repeating x
When several series share the same x values, MATLAB allows a shorthand where you supply one x argument followed by several y vectors. MATLAB then uses the same x for each y, provided their lengths match.
x = 0:0.1:2*pi;
y1 = sin(x);
y2 = cos(x);
y3 = sin(2*x);
plot(x, [y1; y2; y3]);
In this form, [y1; y2; y3] is a matrix where each row is one series. MATLAB interprets each column as a data point, so you get three lines corresponding to the three rows. In order for this to work, all y vectors must have the same length, and their orientation must match the way you form the matrix.
If your y data are column vectors, then stacking them as columns is more natural.
x = (0:0.1:2*pi)';
y1 = sin(x);
y2 = cos(x);
y3 = sin(2*x);
Y = [y1 y2 y3]; % 3 columns
plot(x, Y); % One line per column
Each column in Y becomes a line on the plot that shares the same x.
Adding New Axes to the Same Figure
Sometimes you want two separate sets of axes in the same figure, instead of overlaying everything in one axes. For example, you might want two independent plots that share space in the same window, but do not share the same axis limits or scales.
You can create a new axes object in the same figure at a specific position using the axes function with the 'Position' property. The position is specified as [left bottom width height] in normalized units between 0 and 1.
x = 0:0.1:10;
y1 = sin(x);
y2 = exp(-0.3*x);
figure;
ax1 = axes('Position', [0.1 0.1 0.35 0.8]);
plot(ax1, x, y1);
title(ax1, 'Sine');
ax2 = axes('Position', [0.55 0.1 0.35 0.8]);
plot(ax2, x, y2);
title(ax2, 'Exponential decay');
This code uses one figure with two separate axes side by side. Each plot call specifies which axes to draw in by passing ax1 or ax2 as the first argument. Each axes object has its own limits, labels, and title.
Although other layout methods exist, such as grid layouts, using axes directly gives you precise control over where each axes appears.
Overlaying Axes for Different Scales with `yyaxis`
It is sometimes useful to show two quantities that share a common x axis but have very different ranges of y values. In that case you can use a left and a right y axis in the same axes area. MATLAB provides the yyaxis command for this purpose.
The basic pattern is to switch the active side, then plot your data for each side.
x = 0:0.1:10;
y1 = sin(x); % Small values
y2 = 100*exp(-0.5*x); % Much larger scale
yyaxis left;
plot(x, y1);
ylabel('Sine');
yyaxis right;
plot(x, y2);
ylabel('Exponential');
xlabel('x');
title('Two scales in one plot');The left and right y scales are adjusted separately. This approach still uses a single x axis and keeps related information together while preserving visibility for both series.
Managing Axes and Figure State When Adding Plots
When adding multiple plots in one figure, it is important to be clear about which axes you are drawing into. If you create several axes explicitly and then call plot without specifying an axes, MATLAB uses the current axes. The current axes are typically the last one created or clicked in an interactive session.
To avoid confusion, especially in scripts, it is a good habit to store handles to axes in variables and pass them explicitly to plotting functions.
figure;
ax1 = axes('Position', [0.1 0.1 0.8 0.35]);
ax2 = axes('Position', [0.1 0.55 0.8 0.35]);
x = 0:0.1:10;
plot(ax1, x, sin(x));
plot(ax2, x, cos(x));
Here it is clear that the sine curve goes into ax1 and the cosine curve goes into ax2, regardless of which axes is current.
When you use hold on, it applies to the current axes only. If you have multiple axes in a figure and you want to add more plots to a particular one, either make that axes current by clicking on it in the figure window, or by calling axes(axHandle) before using hold on, or by using plot(axHandle, ...) consistently.
Views: 0
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
-
Comments
Please login to add a comment.
Don't have an account? Register now!