0% found this document useful (0 votes)
10 views32 pages

MATLAB Graphs and Data Visualization

Chapter 4 of the document discusses creating and modifying graphs and data visualizations in MATLAB, emphasizing the use of high-level plotting functions for effective scientific documentation. It covers various plotting cases, appearance modifications, annotations, axis limits, and tools for organizing multiple plots. Additionally, it introduces specialized plotting functions and the interactive 'Plot' tab for customizing visualizations without coding.

Uploaded by

bacstudy33
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views32 pages

MATLAB Graphs and Data Visualization

Chapter 4 of the document discusses creating and modifying graphs and data visualizations in MATLAB, emphasizing the use of high-level plotting functions for effective scientific documentation. It covers various plotting cases, appearance modifications, annotations, axis limits, and tools for organizing multiple plots. Additionally, it introduces specialized plotting functions and the interactive 'Plot' tab for customizing visualizations without coding.

Uploaded by

bacstudy33
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

University of Algiers 1

Faculty of science
Computer Science department
Programming Tools for Mathematics (OPM)

Chapter 4: graphs and data


visualization in MATLAB
Prepared by: Dr. Sarah Madi
Introduction
• Creating high-quality graphs is essential for scientific document
writing in MATLAB.
• Recent MATLAB versions offer improved visualization capabilities.
• High-level graphical functions simplify the creation of well-structured
graphs.
• Plots help visualize data, compare datasets, track changes, and show
distributions.
• Graphs can be generated programmatically using MATLAB functions
or interactively via the Plots tab.
Plotting functions and 2D data
• The plot function is MATLAB's primary tool for creating plots.
• It works with vectors or matrices to generate line plots.
• Points are connected based on provided coordinate arguments.
• The basic syntax is plot(x, y), where x and y have matching
dimensions.
• Each column in x represents X-axis values, while corresponding y
columns define Y-axis values.
Please notice that we can have multiple cases as follow:
• Case1: If it contains two vectors of the same size as arguments:
• it considers the values of the first vector as the elements of the X-axis (abscissas) and the
values of the second vector as the elements of the Y-axis (ordinates).

• Here, x provides explicit X-axis values.


• y defines the corresponding Y-axis values.
• MATLAB plots (x(i), y(i)) pairs, resulting in a properly scaled graph.
• Case 2: If it contains a single vector as an argument: it considers the values of the vector as the elements of the Y-axis
(ordinates), and their relative positions will define the X-axis (abscissas). Here is an example:

Since only one vector v is given, MATLAB assumes:


• The indices (1, 2, 3, …) as the X-axis values.
• The elements of v as the Y-axis values.
• Case 3: If it contains two matrices as arguments: it considers the values of each column of the first matrix
as the elements of the X-axis and the values of each column of the second matrix as the values of the Y-axis.

since A and B are both 3×3 matrices and the plot(A, B)


command treats:
• Each column of A as x values.
• Each corresponding column of B as y values
• This results in three curves (one for each column),
where:
The first column of A is plotted against the first column of B.
The second column of A is plotted against the second column of B.
The third column of A is plotted against the third column of B.
• Case 4: If it contains a single matrix as an argument: it considers the values of each column as the
elements of the Y-axis, and their relative positions (the row number) as the values of the X-axis. This results
in multiple curves (one for each column).

As an example now, if you use plot(A) instead of plot(A, B) from the previous example,
as follows:

MATLAB assumes:
• Each column of A represents Y values.
• The row index (1, 2, 3, …) is used as the X values.
This means that each column of A is plotted as a separate curve,
using its row index as the X values.
Note: It is evident that as the number of coordinates increases, the curve becomes
more precise.
For example, to plot the function y=sin(x) over the interval [0,2π] with a step size of pi/3 or pi/12:

Notice how decreasing the step size means more points and that will lead to better precision.
In the following example, x is a vector, while Y is a matrix with two columns. The plot function automatically
plots both columns of Y against x.
Modifying the appearance of the curves
• The plot command allows extra parameters to define colors, marker
styles, and line styles.
• These parameters are specified as strings or symbols.
• A string can combine a color, a line style, and a point marker.
• If no line style is given, only markers are displayed.
• A table provides the meanings of various symbols used (next slide).

These symbols can be combined in the third argument of the plot() function in
the form: plot (x, y, 'lineSpec') to include line specifications such as Line style,
marker, and color.
Color Line style Marker
Symbol Meaning Symbol Meaning Symbol Meaning
y Yellow : Dotted line s Square
m Magenta -. Dash-dot line d Diamond
c Cyan -- Dashed line ^ Upward
triangle
r Red - Solid line v Downward
triangle
g Green > Right triangle
b Blue < Left triangle
w White p Pentagram
k Black h Hexagram
o Circle
+ Plus sign
plot(x, y, 'r--o') % Red dashed line with circle markers . Point marker
plot(x, y, 'b:*') % Blue dotted line with star markers * Star
plot(x, y, 'g^') % Green upward triangle markers (no line) x Cross
Plot the function y=sin(x) for x∈[0,2π] with a step size of π/6. By changing the specifications,
different results can be obtained. We need:
• a plot with a red color, dotted line and a star marker
• a plot with a black color, dashed dotted line and an upward triangle marker
• a plot with a blue color, solid line and a pentagram marker
Annotations of figures
• Adding textual descriptions in figures improves clarity and understanding.
• Important points can be highlighted with comments explaining their significance.
• Use title ('Figure Title') to set a title for the figure.
• Label axes with xlabel('X-axis label') and ylabel('Y-axis label').
• Add text at specific coordinates using text (x, y, 'Message').
• Use gtext ('Message') to place text manually with the mouse.
• Enable or disable the grid with grid on and grid off.
Modifying axis limits
• By default, MATLAB automatically determines the limits (minimum
and maximum) for the X and Y axes and selects an appropriate
scaling. However, you can manually control the appearance of the
axes using the axis command
Function Description MATLAB Command
Set custom axis limits Defines the min and max values for X axis([xmin xmax ymin ymax]) or
and Y axes. axis([xmin, xmax, ymin, ymax])
Reset to default limits Returns to automatic axis scaling. axis auto

With access limits: Example:


With axis auto:
Here are some additional axis options:

Function Description MATLAB Command


Square axes Makes both axis lengths axis square
equal but does not affect
scaling.
Equal scaling Ensures the same scale for axis equal
both axes.
Reset to default Returns to automatic axis axis auto
settings.
Hide axes Makes the axes invisible. axis off
Show axes Restores the visibility of axis on
axes.
Plotting functions and 3D data
• MATLAB offers functions to plot 3D curves on three axes.
• Use plot3(X, Y, Z) to visualize 3D points, where X, Y, and Z are vectors
or matrices.
• The 3D rotation tool allows users to adjust the viewing angle
interactively.
• Enabling the grid enhances visualization.
• The zlabel function labels the Z-axis in 3D plots.
• MATLAB provides functions for generating 3D geometric shapes like spheres and
cylinders.
• These shapes are useful for 3D modeling, simulations, and visualizations.
• The sphere(n) function generates a unit sphere with n divisions.
• Syntax: [X, Y, Z] = sphere(n);
• Default: If n is omitted, MATLAB uses n = 20.
• The cylinder(r, n) function creates a cylinder with a given radius r and n divisions.
• Syntax: [X, Y, Z] = cylinder(r, n);
• Default: If r is omitted, MATLAB assumes a unit cylinder (radius = 1).
• A cone is a special case of a cylinder with a base radius of 0.
• Syntax: [X, Y, Z] = cylinder([0 r], n);
• 3D shape functions (sphere, cylinder, ellipsoid) generate X, Y, and Z coordinate
matrices.
• These matrices define a 3D surface for visualization.
The mesh and surf functions control surface appearance in 3D plots.
Both mesh and surf are used for 3D plotting but differ in visualization style.

Notice how mesh(X, Y, Z); Shows only the edges of the sphere
(wireframe) and surf(X, Y, Z); → Creates a solid and smooth-colored
sphere
Tools for organizing the graphs
• MATLAB provides three high-level tools to organize plots effectively:
• hold on – Retains previous plots on the same axes instead of overwriting them.
• figure – Opens a new figure window for a separate plot.
• subplot – The subplot(m, n, p) function divides a figure into a grid of m rows and n
columns, then places the plot in position p (counted left to right, top to bottom).
•tiledlayout: creates a tiled chart layout for displaying multiple plots in the current figure
In addition to the other tools that we already presented during this chapter such
as:
• close – Closes a specific figure window or all figures.
• legend – Adds a legend to a plot.
• title, xlabel, ylabel – Labels and titles for better visualization.
• grid on/off – Toggles grid visibility for clarity.
Based on the listed tools, there are three possible approaches if you want to plot multiple
graphs:
Case 1: Plots in the Same Axes
1. Use `hold on` to overlay multiple plots on the same axes.
2. This command retains the current plot, allowing new
plots to be added.
3. To revert to overwriting mode, use `hold off`.
4. Additional commands like `grid on/off` improve
visualization.
5. Example code demonstrates `figure`, `hold on/off`, and
`grid on/off`.
Case 2: plots in the same window:
This approach allows a single figure window to be divided into multiple sections, each
containing a different plot.
The function used to achieve this is subplot. With the syntax:
subplot(m, n, p)
MATLAB divides the figure into an m × n grid of axes and places the plot in the p-th
position.
In the previous example we used all subplots in the grid. We can also
span one subplot over two grids as in the following example:
A more flexible alternative to subplot is tiledlayout, which provides better control over
spacing and alignment.
The syntax is:
tiledlayout(m, n);
nexttile(p);
plot(x, y);
This method improves the appearance and organization of multiple plots within the same
figure.
Case 3: Graphs in different windows:
The figure function in MATLAB allows opening new graphical windows. Each window has a
unique number, with the first one being numbered 1.
• figure(n), where n is an integer, either creates a new figure with number n or, if it
already exists, brings it to the foreground as the active figure.
• The number of the currently active window can be retrieved using gcf (Get handle
to current figure).
• However, an active figure might not always be visible if it is covered by other
windows. The shg (Show graph window) command brings the figure to the front.

This example creates two separate figure windows, plots


different data in each, retrieves the current active figure, and
ensures visibility using shg.
Special MATLAB functions
• MATLAB offers numerous specialized plotting functions beyond the
basic plot().
• These functions help visualize data in different formats, such as bar
charts, histograms, scatter plots, and 3D surface plots.
• Some functions support statistical analysis, while others aid in 3D
modeling or data distribution representation.
• Geographic visualizations are also possible with specific MATLAB
plotting tools.
• A table can summarize different plotting functions, their syntax, use
cases, and examples.
Function Description Example Use Case
plot Line plot plot(x, y) Basic 2D plotting
bar Bar chart bar(x, y) Comparing values
histogram Histogram histogram(data, Data distribution
bins)
scatter Scatter plot scatter(x, y) Data correlation
pie Pie chart pie(data) Proportional data
stem Discrete data plot stem(x, y) Signal processing
stairs Step plot stairs(x, y) Discrete changes
polarplot Polar coordinates polarplot(theta, r) Circular data
plot
mesh 3D mesh surface mesh(X, Y, Z) 3D visualization
surf 3D surface plot surf(X, Y, Z) Smooth 3D surfaces
The "Plot" tab in MATLAB provides an interactive way to create, customize, and manage plots without writing code. It
allows users to select different plot types, modify their appearance, and add labels, titles, and legends easily.
Where to Find the "Plot" Tab?
•The "Plot" tab is available in MATLAB's Toolstrip (ribbon) at the top of the interface.
•It appears when you create a figure or select a plot.
Which MATLAB function can overlay multiple plots in the same How can you add a grid to a MATLAB plot?
figure? A) grid on
A) hold on B) grid()
B) subplot() C) showgrid()
C) figure() D) grid enable
D) grid on
What is the purpose of the subplot() function?
A) To create multiple figures
B) To display multiple plots in the same figure
C) To add grid lines to a plot
D) To set the title of a plot
Which function is used to control the axes limits of a plot?
A) axis()
B) xlim()
C) ylim()
D) All of the above
If you want to display multiple plots in different figure windows,
what command should you use?
A) subplot()
B) hold on
C) figure()
D) axes()

You might also like