Showing posts with label Plotting in MATLAB. Show all posts
Showing posts with label Plotting in MATLAB. Show all posts

Sunday, March 8, 2026

How to Use Subplot in MATLAB – Multiple Plots on One Figure Explained with Examples

 

MATLABit

Discover how to represent numerical data clearly and effectively using histograms in MATLAB. This guide explains how histograms illustrate frequency distribution by grouping data into continuous intervals known as bins. It introduces the basic histogram command, shows how to adjust the number of bins, specify bin centers, and understand frequency counts.

Histograms are valuable for revealing important data characteristics such as concentration, variability, skewness, and possible gaps within a dataset. MATLAB offers flexible tools to modify bin width and extract numerical outputs, including frequency values and bin positions, allowing for more accurate and meaningful analysis.

The tutorial also discusses the significance, practical applications, and useful tips for creating clear and reliable histograms across various fields, including education, research, engineering, business analytics, and environmental studies. Whether you are a beginner learning data visualization or a professional analyzing complex datasets, this guide will help you convert raw numerical information into informative and visually appealing graphical displays using MATLAB.

MATLAB Subplot Example – Multiple Plots in One Figure

The images below demonstrate how to use the subplot command in MATLAB to create multiple plots within a single figure window. This method helps in comparing graphs efficiently and improving data visualization clarity.

MATLAB subplot command example code for multiple plots

Figure 1: MATLAB subplot syntax and example code.

Four subplots arranged in one MATLAB figure window

Figure 2: Four plots arranged using subplot(2,2,p) in MATLAB.

MATLAB subplot showing multiple graph windows comparison

Figure 3: Comparison of multiple plots displayed in a single MATLAB figure.

Using MATLAB subplots is essential for engineering students, researchers, and data analysts who need to compare multiple datasets efficiently.

Table of Contents

Introduction

In MATLAB, multiple graphs can be displayed within the same Figure Window by using the subplot command. This command is especially useful when comparing different plots side by side on a single page. The general syntax of the command is subplot(m, n, p), where m represents the number of rows, n represents the number of columns, and p specifies the position of the active subplot.

When executed, the subplot command divides the Figure Window into a grid consisting of m × n rectangular sections. These sections are arranged in a matrix-like structure, similar to elements in a table with rows and columns. Each subplot is assigned a unique number starting from 1 up to m × n. Numbering begins at the top-left corner, which is subplot 1, and increases from left to right across each row. After completing a row, numbering continues on the next row below until reaching the bottom-right subplot.

By selecting a specific value for p, the chosen subplot becomes active. Any subsequent plotting or formatting commands will apply only to that selected section, allowing organized and clear presentation of multiple graphs in one figure.

Significance

The subplot command in MATLAB is highly significant because it allows multiple graphs to be displayed within a single Figure Window. This capability is extremely useful when comparing different datasets, functions, or experimental results side by side. Instead of opening several separate figure windows, subplot organizes multiple visualizations in a structured grid format, making analysis more efficient and visually clear.

One major advantage of using subplots is improved comparison. When graphs are placed next to each other on the same page, differences and similarities between trends, shapes, peaks, and variations become easier to identify. This is particularly important in scientific research, engineering analysis, and data science, where visual comparison often leads to better understanding and interpretation of results.

Another important significance is space optimization. Subplots allow better use of the Figure Window by dividing it into multiple sections. This is especially helpful when preparing reports, presentations, or printed materials, as all relevant graphs can be shown on a single page. It enhances clarity and reduces the need to switch between multiple figures.

Additionally, subplot improves organization and presentation quality. Each plot can have its own title, labels, and formatting while remaining part of a unified figure. This structured arrangement helps maintain logical flow when presenting step-by-step analysis, such as comparing original data with processed data or theoretical results with experimental findings.

Overall, the subplot command enhances visualization efficiency, supports better comparative analysis, and improves the overall presentation of graphical data in MATLAB.

Use of Subplot

The subplot command in MATLAB plays an important role in organizing and presenting multiple graphical outputs within a single Figure Window. In data analysis, engineering applications, and scientific research, it is often necessary to compare different functions, signals, or datasets simultaneously. Instead of opening separate figure windows for each graph, the subplot command divides the display area into a grid of smaller plotting regions. This structured arrangement improves clarity, saves time, and enhances interpretation.

The general syntax of the command is subplot(m, n, p), where m represents the number of rows, n represents the number of columns, and p indicates the position of the current subplot. The numbering starts from the top-left corner and increases from left to right across each row. Once a subplot is selected, any plotting command applies only to that specific region.

For example, suppose we want to plot four basic mathematical functions: sine, cosine, exponential, and logarithmic functions. Instead of creating four separate figure windows, we can use a 2×2 grid:

x = 0:0.1:10;

subplot(2,2,1)
plot(x, sin(x))
title('Sine Function')

subplot(2,2,2)
plot(x, cos(x))
title('Cosine Function')

subplot(2,2,3)
plot(x, exp(x))
title('Exponential Function')

subplot(2,2,4)
plot(x, log(x))
title('Logarithmic Function')

In this example, the figure window is divided into four equal sections arranged in two rows and two columns. Each function is displayed in its own subplot, making it easy to visually compare their shapes and behaviors. For instance, we can quickly observe that sine and cosine are periodic, while the exponential function increases rapidly and the logarithmic function grows slowly.

Another practical example can be seen in signal processing. Suppose an engineer wants to compare an original signal with a noisy signal and its filtered version. Using subplot, all three signals can be displayed together:

t = 0:0.01:2*pi;
original = sin(t);
noise = 0.5*randn(size(t));
noisy_signal = original + noise;
filtered_signal = smoothdata(noisy_signal);

subplot(3,1,1)
plot(t, original)
title('Original Signal')

subplot(3,1,2)
plot(t, noisy_signal)
title('Noisy Signal')

subplot(3,1,3)
plot(t, filtered_signal)
title('Filtered Signal')

Here, the figure is divided into three rows and one column. This vertical arrangement clearly shows how noise affects the signal and how filtering improves it. Such visualization is extremely useful for understanding system performance.

Subplot is also beneficial in educational settings. Teachers can demonstrate step-by-step transformations of a function, such as shifting, scaling, or reflecting graphs, by placing each transformation in a separate subplot. This allows students to easily track changes and understand mathematical concepts visually.

Furthermore, subplot improves presentation quality in reports and research papers. Multiple related graphs displayed on the same page provide a compact yet comprehensive overview of results. Each subplot can include individual titles, axis labels, grid lines, and formatting, ensuring both clarity and professional appearance.

In summary, the subplot command is a powerful visualization tool that enhances comparison, organization, and communication of graphical data. By structuring multiple plots within a single figure, it simplifies analysis and improves overall understanding.

Applications

The subplot command in MATLAB has wide applications in engineering, science, research, and education. One major application is in data analysis, where multiple datasets need to be compared simultaneously. By placing related graphs in one figure window, researchers can easily observe patterns, differences, and trends without switching between multiple figures.

In signal processing, subplot is commonly used to display original, noisy, and filtered signals together for performance evaluation. Similarly, in control systems, engineers compare input signals, system responses, and error signals within a single organized layout. This helps in analyzing system behavior effectively.

In mathematics and physics education, subplot assists in demonstrating transformations of functions, comparisons of theoretical and experimental results, and step-by-step graphical explanations. It simplifies intricate concepts via illustration.

Subplot is also useful in image processing, where original, processed, and enhanced images are displayed side by side. Additionally, in research publications and presentations, it improves the professional appearance of graphical results by organizing multiple related plots on a single page.

Overall, subplot enhances visualization efficiency, supports comparative analysis, and improves the clarity of graphical communication.

Conclusion

In conclusion, the subplot command in MATLAB is a powerful and practical tool for displaying multiple graphs within a single Figure Window. It allows users to organize plots in a structured grid format, making comparison and analysis much easier. By dividing the figure into rows and columns, subplot helps present related data clearly and efficiently without opening multiple windows.

This feature is especially valuable in engineering, scientific research, data analysis, and education, where visual comparison plays an important role in understanding results. It enhances presentation quality, saves space, and improves overall workflow. Each subplot can be customized with its own titles, labels, and formatting, ensuring clarity and professionalism.

Overall, the subplot command improves data visualization, supports better interpretation, and makes graphical representation more organized and effective.

Tips in MATLAB

When using the subplot command in MATLAB, proper planning of the grid layout is important. Before writing the code, decide how many plots are needed and choose suitable values for rows and columns to ensure a clean arrangement. Avoid overcrowding too many plots in a small figure window, as this can make graphs difficult to read.

Always add clear titles, axis labels, and grid lines to each subplot to improve readability. Using consistent axis limits across related plots helps in accurate comparison. The sgtitle command can be used to add an overall title for the entire figure, making the presentation more professional.

Adjust spacing if necessary using layout tools such as tiledlayout in newer MATLAB versions for better control. Finally, keep formatting consistent, including font size and line style, to maintain a neat and organized visual appearance.

© 2025-2026 MATLABit. All rights reserved.

Friday, January 2, 2026

Plotting 2D Graphs in MATLAB: A Beginner’s Guide

 

MATLABit

MATLAB, short for MATrix LABoratory, is a powerful programming language and software environment developed by MathWorks. It is widely used in engineering, scientific research, academic instruction, and algorithm development due to its strengths in numerical computation, data analysis, and graphical visualization. MATLAB makes it easy to create and customize 2D plots. In this guide, beginners will learn how to plot data points, add labels, customize axes, and create visually appealing 2D graphs for better analysis and presentation of results.

Table of Contents

Introduction

Plots are an essential tool for visualizing and interpreting numerical data. In scientific, engineering, and mathematical fields, graphical representation helps transform raw numbers into meaningful insights. MATLAB is widely used for numerical computation and data visualization because it offers a rich collection of commands for generating professional-quality plots with minimal effort.

Visualization plays a vital role in understanding trends, validating theoretical models, comparing experimental results, and presenting findings clearly. MATLAB supports a variety of plot types, including linear and logarithmic plots, bar charts, stair plots, polar plots, and three-dimensional visualizations. Additionally, MATLAB allows full control over plot appearance, including line styles, colors, thickness, markers, grid lines, labels, legends, and annotations.

This chapter focuses on the creation and formatting of two-dimensional plots using MATLAB. The discussion emphasizes the plot command, which is the most commonly used tool for visualizing data in two dimensions. Three-dimensional plotting is addressed separately.

Significance

Plotting in MATLAB is an essential aspect of data analysis, scientific computation, and engineering problem-solving, providing a powerful platform for visualizing data and functions in a variety of formats. MATLAB, short for Matrix Laboratory, is widely used in academia, research, and industry for numerical computation, and one of its most notable features is the ability to create high-quality plots that convey meaningful insights. The significance of plotting in MATLAB can be appreciated from multiple perspectives, including data interpretation, communication, analysis, and research development. Firstly, plotting in MATLAB serves as a primary tool for data visualization. Raw numerical data alone often does not convey useful information, especially when dealing with large datasets or multidimensional data. A well-constructed plot transforms numerical values into visual representations that are easier to understand, interpret, and analyze. Trends, patterns, and anomalies in a dataset can be quickly identified through line plots, scatter plots, bar charts, or surface plots, enabling users to make faster and more accurate decisions based on observed trends. Secondly, plotting enhances data analysis and interpretation. MATLAB offers a variety of plotting functions such as plot, scatter, bar, histogram, surf, and contour, among others, each tailored for specific types of data and purposes. For instance, a line plot can illustrate continuous changes over time, while a bar plot is suitable for comparing discrete categories. By visually representing data, MATLAB allows users to analyze relationships between variables, study functional behavior, and explore correlations in datasets. Advanced features like log-scale axes, error bars, and multiple plots in a single figure provide even deeper insights into data characteristics. Another significant aspect of plotting in MATLAB is its role in model verification and validation. In scientific research, simulations and computational models generate large volumes of data, and visualizing this data through plots allows researchers to verify whether the models behave as expected. For example, plotting the output of a simulation against experimental data can reveal discrepancies or errors in the model. This ability to validate models through graphical analysis is invaluable in fields such as control systems, signal processing, image analysis, and machine learning, where the accuracy of models directly affects real-world applications. In addition, MATLAB plots are crucial for effective communication of results. Whether in research papers, academic presentations, or industrial reports, visual representations of data are more comprehensible than tables of numbers. MATLAB allows customization of plots, including axis labels, titles, legends, colors, and line styles, making visualizations both informative and aesthetically appealing. High-quality plots can effectively convey complex results to audiences, including non-technical viewers, bridging the gap between raw data and human understanding. Plotting also facilitates exploratory data analysis (EDA), which is an essential step before applying advanced algorithms or computational methods. Through plotting, users can detect outliers, assess distributions, and understand variability in data. Histograms can show frequency distribution, while scatter plots reveal clustering patterns or correlations. These insights guide the selection of appropriate statistical methods, machine learning models, or optimization techniques. Furthermore, MATLAB’s plotting capabilities are highly interactive and versatile. Users can zoom, pan, rotate, and annotate plots in real-time, allowing detailed examination of specific regions of interest. Three-dimensional plotting and surface visualization help understand multivariate relationships, while dynamic plots and animations can illustrate changes over time or iterations. This interactivity enhances learning, teaching, and research, as it allows users to explore data in ways that static images cannot. Finally, plotting in MATLAB contributes significantly to innovation and problem-solving. Visual insights often lead to hypotheses, new research questions, or design improvements in engineering applications. By observing data in graphical form, researchers and engineers can identify trends or issues that may not be apparent from numerical analysis alone, fostering creativity and innovation. In conclusion, plotting in MATLAB is a fundamental component of computational and scientific work. It transforms raw data into meaningful visual information, supports data analysis, validates models, enhances communication, and aids in research and problem-solving. The ability to create, customize, and interact with plots makes MATLAB an indispensable tool for professionals and students alike. Ultimately, plotting in MATLAB is not merely about drawing graphs—it is about understanding data, discovering insights, and conveying information effectively, making it an indispensable skill in modern scientific and engineering practices.

How to Use Plot Command in MATLAB?

Role of Two-Dimensional Plots

Two-dimensional plots are frequently used to display how one variable changes with respect to another. Such plots are essential for analyzing relationships between variables and for identifying trends or patterns within datasets.

A well-designed plot can reveal important information that may not be obvious from numerical data alone. It can help detect anomalies, compare datasets, and improve communication in technical reports and presentations.

The MATLAB plot Command

The most basic tool for creating two-dimensional graphs in MATLAB is the plot command. In its simplest form, it takes two vectors as input arguments: one for the horizontal axis and one for the vertical axis.

When the command is executed, MATLAB opens a Figure Window (if it is not already open) and displays the graph using default settings.

Plotting a Single Vector

If only one vector is supplied to the plot command, MATLAB automatically uses the element index of the vector as the horizontal axis. This feature is useful for visualizing sequences, signals, or iterative results.

Default Plot Characteristics

By default, MATLAB creates plots with linear axes, automatic axis limits, and a blue solid line. No grid, title, or axis labels are included unless specified by the user. These defaults provide a simple starting point for data visualization.

Line Specifiers in MATLAB

MATLAB allows users to control line appearance using line specifiers. These specifiers define the line style, color, and marker type. They are written as a single string argument within the plot command.

Line Style Options

Line Style Specifier
Solid -
Dashed --
Dotted :
Dash-dot -.

Line Color Options

Color Specifier
Redr
Greeng
Blueb
Cyanc
Magentam
Yellowy
Blackk
Whitew

Marker Options

Marker Type Specifier
Circleo
Plus+
Star*
Point.
Squares
Diamondd
Crossx
Triangle (up)^
Triangle (down)v
Triangle (left)<
Triangle (right)>

Using Plot Properties

Beyond line specifiers, MATLAB provides property name–value pairs for advanced formatting. These properties allow precise control over line thickness, marker size, and marker colors.

Property Name Description
LineWidth Controls the thickness of the plotted line
MarkerSize Specifies the size of the markers
MarkerEdgeColor Sets the marker border color
MarkerFaceColor Defines the marker fill color

Multiple Curves in One Plot

MATLAB supports plotting multiple datasets on the same axes, which is useful for comparing experimental data with theoretical predictions or for visualizing multiple variables together. Legends help distinguish between different curves.

Applications

  • Engineering analysis such as stress–strain relationships
  • Scientific experiments and model validation
  • Medical imaging and algorithm performance evaluation
  • Data science and machine learning visualization
  • Educational demonstrations and teaching materials

Conclusion

Two-dimensional plotting is one of the most fundamental and powerful features of MATLAB. The plot command provides an easy way to visualize relationships between variables, while customization options allow users to produce publication-quality figures.

By mastering line specifiers, plot properties, and formatting options, users can greatly enhance the clarity and impact of their data presentations. These skills form a foundation for more advanced visualization techniques in MATLAB.

Tips in MATLAB

  • Always label axes clearly and include units
  • Use legends when plotting multiple datasets
  • Increase line width for presentations and publications
  • Use grid lines to improve readability
  • Maintain consistent styles across figures
  • Avoid overcrowding plots with excessive markers
  • Save figures in high resolution for reports and journals

© 2025-2026 MATLABit. All rights reserved.

Multiple Figure Windows in MATLAB – Creating and Managing Multiple Plots

  MATLABit Learn how to create and manage multiple figure windows in MATLAB to display and compare different plots efficiently. This ...