0% found this document useful (0 votes)
47 views45 pages

I. Overview of MATLAB Plotting

This document discusses MATLAB plotting tools and functions. It covers topics like plotting different graph types, adding labels and titles, arranging multiple graphs, selecting different plot types, editing existing plots, and preparing graphs for presentation. Basic plotting functions like plotting multiple datasets and specifying line styles are also described.

Uploaded by

Bassmala Baraa
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)
47 views45 pages

I. Overview of MATLAB Plotting

This document discusses MATLAB plotting tools and functions. It covers topics like plotting different graph types, adding labels and titles, arranging multiple graphs, selecting different plot types, editing existing plots, and preparing graphs for presentation. Basic plotting functions like plotting multiple datasets and specifying line styles are also described.

Uploaded by

Bassmala Baraa
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
You are on page 1/ 45

Chapter 3: Graphics

I. Overview of MATLAB Plotting


Plotting Tools
Both types: lineseries and stem
Lineseries graph type Stem graph type
Define the function figure(2)
plot(t,y) stem(t,y)
y(t)=exp(sin(t) plotyy(t,y,t,y,'plot','stem')
xlabel('X Axis') xlabel('X Axis')
t = 0:pi/20:2*pi; xlabel('X Axis')
ylabel('Y Axis') ylabel('stem Y Axis')
y = exp(sin(t)); ylabel('Plot Y Axis')
title('plot y(t)=exp(sin(t)') title('stem y(t)=exp(sin(t)')
title('Two Y Axes')

Adding a label for the y-axis that corresponds to the stem plot is easily accomplished.

Double click to open


the Axes Property
Click to open the Plot Browser Editor Fill in this field 1
Arranging Graphs Within a Figure
You can place a number of axes within a figure by selecting the layout you want from the Figure Palette the View menu. For
example, the following picture shows how to specify four 2-D axes in the figure.

You can also use the subplot command to


create multiple axes

2
Selecting Plot Types
You can use the Plot Catalog to select from a variety of techniques for plotting data. To access the Plot Catalog,
1. Select the variables you want to plot in the Figure Palette.
2. Right-click to display the context menu.
3 Select Plot Catalog to display the catalog.

3
II. Editing Plots
Plot Editing Mode
Enabling Plot Edit Mode
To enable plot edit mode, click the arrowhead in the figure toolbar:
You can also select Edit Plot from the figure Tools menu.
Setting Object Properties
Once you have enabled plot edit mode, you can select objects by clicking on them in the graph. Selection handles appear and
indicate that the object is selected. Select multiple objects using Shift+click.

Right-click with the pointer over the selected object to display the object’s context menu.

The context menu provides quick access to the most commonly used operations and properties

Using the Property Editor


In plot edit mode, double-clicking on an object in a graph starts the Property Editor with that object’s major properties
displayed. The Property Editor provides access to the most used object properties. It is updated to display the properties of
whatever object you select.

4
Accessing All Properties — Property Inspector (More Properties)
The Property Inspector is a tool that enables you to access all object properties. If you do not find the property you want to set
in the Property Editor, click the ’’More Properties’’ button to display the Property Inspector. You can also use the ’’inspect’’
command to start the Property Inspector.

The following picture shows the Property Inspector displaying the properties of a graph’s axes. It lists each property and
provides a text field or other appropriate device (such as a color picker) from which you can set the value of the property.

As you select different objects, the Property Inspector is updated to display the properties of the current object.

5
III. Example using MATLAB Plotting Tools
Suppose you want to graph the function 𝑦 = 𝑥 3 over the 𝑥 domain -1 to 1. The first step is to generate the data to plot:

x = -1:.1:1; % Define the range of x


y = x.^3; % Raise each element in x to the third power

Now that you have generated some data, you can plot it using the MATLAB plotting tools. To start the plotting tools, type:

plottools

Plotting Two Variables


A simple line graph is a suitable way to display x as the independent variable and y as the
dependent variable. To do this, select both variables (click to select, then Shift-click to select
again), then right-click to display the context menu.

Select ’’Plot Catalog’’ from the menu and then ’’plot(x,y)’’. MATLAB creates the line graph in the
figure area. The blue squares indicate that the line is selected and you can edit its properties with
the Property Editor.

6
Changing the Appearance
Next change the line properties so that the graph displays only the data point. Use the Property Editor to set
following properties:

7
Adding More Data to the Graph
You can add more data to the graph by defining more variables or by specifying an expression that MATLAB
uses to generate data for the plot. This second approach makes it easy to explore variations of the data already
plotted.
To add data to the graph, select the axes in the Plot Browser and click the Add Data button. When you are
using the plotting tools, MATLAB always adds data to the existing graph, instead of replacing the graph, as it
would if you issued repeated plotting commands. That is, the plotting tools are in a hold on state.

8
IV. Preparing Graphs for Presentation
Suppose you plot the following data and want to create a graph that presents certain information about the data.
x = -10:.005:40;
y = [1.5*cos(x)+4*exp(-.01*x).*cos(x)+exp(.07*x).*sin(3*x)];
plot(x,y)
Modify the Graph to Enhance the Presentation
To obtain a better view, zoom in on the graph using horizontal zoom: after enabling zoom mode from the figure
toolbar, right-click to display the context menu. Select Horizontal Zoom.

Left-click (for example three times) to zoom in on the region containing the fourth and fifth positive peaks of the
graph and use the panning tool to start the graph from y = -15 instead of -20. Next, use Data Cursor and Create
New Datatip (right click), respectively to label both peaks on the graph.

Finally, add:
- text annotation using the Insert text menu,
- axis labels using the commands xlabel and ylabel
- Title using the command title, in order to obtain the following graph. 9
You can add the title and axis labels using the following commands:

title ('y = 1.5cos(x) + 4e^{-0.01x}cos(x) + e^{0.07x}sin(3x)')


xlabel('X Axis')
10
ylabel('Y Axis')
Exporting the Graph
Exporting a graph is the process of creating a standard graphics file format of the graph (such as EPS, TIFF, JPEG),
which you can then import into other applications like word processors, drawing packages, etc.
This example exports the graph as a JPEG file with the following requirements:
• The size of the picture when imported into the word processor document should be four inches wide and three
inches high.
• All the text in the figure should have a size of 8 points.
Set the size of the graph in the exported file.

To set the size, select Export Setup from the


figure File menu.

11
To set the font size of all the text in the graph, select Fonts in the Export Setup dialog’s Properties selector.
Then select Use fixed font size and enter 8 in the text box.

12
Finally, to set the file format, click the Export button. MATLAB displays a Save As dialog that enables you to
specify a name for the file as well as select the type of file format you want to use.

13
V. Basic Plotting Functions
Multiple Data Sets in One Graph
Multiple x-y pair arguments create multiple graphs with a single call to plot.

For example, these statements plot three related functions of x, with each curve in a separate distinguishing color.
x = 0:pi/100:2*pi;
y1 = sin(x);
y2 = sin(x-.25);
y3 = sin(x-.5);

plot(x,y1,x,y2,x,y3)

The legend command provides an easy


way to identify the individual plots.

legend('sin(x)','sin(x-.25)','sin(x-.5)')

14
Specifying Line Styles, Colors and Markers
It is possible to specify color, line styles, and markers (such as plus signs or circles) when you plot your data using
the plot command:

plot(x,y,'color_style_marker')

Color style_marker is a string containing from one to four characters (enclosed in single quotation marks)
constructed from a color, a line style, and a marker type:

• Color strings are 'c', 'm', 'y', 'r', 'g', 'b', 'w', and 'k'. These correspond to cyan, magenta, yellow, red, green,
blue, white, and black.
• Line style strings are '-' for solid, '--' for dashed, ':' for dotted, '-.' for dash-dot. Omit the line style for no line.
• The marker types are '+', 'o', '*', and 'x', and the filled marker types are 's' for square, 'd' for diamond, '^' for
up triangle, 'v’ for down triangle, '>' for right triangle, '<' for left triangle, 'p' for pentagram, 'h' for hexagram,
and none for no marker.

If you specify a marker type but not a line style, MATLAB draws only the marker.

15
plot(x,y,'ks')

Y(x)=sin(x), xmin=0, xmax=2𝜋 and dx=0.1

16
plot(x,y,'r:+')

17
Exercise
You might want to use fewer data points to plot the markers than to plot the lines. Write a matlab code
which plot the sine function in one period using a dot and place the markers at every tenth data points.

Solution x1 = 0:pi/100:2*pi;
x2 = 0:pi/10:2*pi;
plot(x1,sin(x1),'r:',x2,sin(x2),'r+')

18
Imaginary and Complex Data
When the argument of plot is complex, the command is a shortcut for a graph of the real part versus the
imaginary part.

Therefore,

plot(Z)

where Z is a complex vector, is equivalent to

plot(real(Z),imag(Z))
For example,

theta = 0:pi/10:2*pi;
plot(exp(i*theta),'-o')

19
The plot command draws a 20-sided polygon with little circles at the vertices.

20
The command axis equal makes the individual tick-mark increments on the x- and y-axes the same
length, which makes this plot more circular in appearance.

21
Figure Windows
Graphing functions automatically open a new figure window if there are no figure windows already on the screen. If
a figure window exists, MATLAB uses that window for graphics output. If there are multiple figure windows open,
MATLAB targets the one that is designated the “current figure” (the last figure used or clicked in).

To make an existing figure window the current figure, you can click the mouse while the pointer is in that window or
you can type

figure(n)

where n is the number in the figure title bar. The results of subsequent graphics commands are displayed in this
window.

To open a new figure window and make it the current figure, type

figure

Example
Plot in the following order : (i) the function y1 = sin(x-.1) on Figure 1, (ii) y2 = sin(x-.2) on Figure 2, (iii) y5 = sin(x-.5) on
Figure 5 and finally y = sin(x) on Figure 2.

22
Solution:
y1 = sin(x-.1); figure(5) hold on
plot(x,y1) y5 = sin(x-.5); plot(x,y)
figure plot(x,y5) hold off
y2 = sin(x-.2); y = sin(x);
plot(x,y2) figure(2)

Controlling the Axes


Setting Axis Limits
By default, MATLAB finds the maxima and minima of the data and chooses the axis
limits to span this range. The axis command enables you to specify your own limits:

axis([xmin xmax ymin ymax])

or for three-dimensional graphs, Example:

axis([xmin xmax ymin ymax zmin zmax]) Plot y(x)=cos(x) for −2𝜋 ≤ 𝑥 ≤ 2𝜋 and then
show the positive part of the plot −𝜋 ≤ 𝑥 ≤ 𝜋
Use the command

axis auto

to reenable MATLAB automatic limit selection. 23


1
Setting axis aspect ratio
0.8
The command axis enables you to specify a number of
predefined modes. For example, 0.6

axis square 0.4

makes the x-axis and y-axis the same length. 0.2


axis auto normal
axis equal 0

sets the aspect ratio so that the data units are the same in -0.2
every direction. -0.4
axis auto normal
-0.6
returns the axis scaling to its default automatic mode.
-0.8

-1
0 1 2 3 4 5 6 7
y=sin(x) y=sin(x)
1

0.8 2

0.6 1.5

0.4 1

0.2 axis square 0.5 axis equal


0 0

-0.2 -0.5

-0.4 -1

-0.6 -1.5

-0.8 -2
24
-1
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6
Setting Grid Lines
The grid command toggles grid lines on and off. The statement
grid on
turns the grid lines on, and
grid off
turns them back off again.

y=sin(x) y=sin(x)
1 1

0.8 0.8

0.6 0.6

0.4 0.4

0.2 0.2

0 0

-0.2 -0.2

-0.4 -0.4

-0.6 -0.6

-0.8 -0.8

-1 -1
0 1 2 3 4 5 6 7 0 1 2 3 4 5 6 7

grid on grid off 25


Axis Labels and Titles
The xlabel, ylabel, and zlabel commands add x-, y-, and z-axis labels. The title command adds a title at the top of
the figure and the text function inserts text anywhere in the figure.
You can produce mathematical symbols using LaTeX notation in the text string.

Example
Graph of the sine function
1

0.8

0.6

0.4

0.2
sin(t)

-0.2
Note the odd symmetry.
-0.4

-0.6

-0.8

-1
-3 -2 -1 0 1 2 3 26
-  t  
Saving Workspace Data Reload saved data
You can save the variables in You can reload saved data using the Import
your workspace using the Save Data item in the Matlab home menu.
Workspace As item in the figure
File menu.

You can also reload saved data using the


Import Data item in the figure File menu.

27
Saving figures that are compatible with previous version of MATLAB
Create backward-compatible FIG-files by typing the command:
hgsave('filename','-v6')
The argument 'filename‘ saves the current figure to a file named filename.
The argument '-v6' saves the FIG-file in a format that can be loaded by versions prior to MATLAB® 7.

VI. Mesh and Surface Plots


Visualizing Functions of Two Variables
To visualize a function of two variables f(x,y) using Matlab, we need to produce first the coordinates of a rectangular grid
(X,Y). To do that, one can use the command meshgrid.

[X,Y] = meshgrid(Vx,Vy) replicates the grid vectors Vx and Vy to produce the coordinates of a rectangular grid (X,Y).
Example: To evaluate the function 𝑓 𝑥, 𝑦 = 𝑥 + 𝑦 over the range −2 ≤ 𝑥 ≤ 2, −4 ≤ 𝑦 ≤ 4, we need to produce firs
the coordinates of a rectangular grid using the command:

[X,Y] = meshgrid(-2:.2:2, -4:.4:4);

and then evaluate the function 𝑓

F = X+Y;
In this case, MATLAB defines a surface by the z=f(x,y) coordinates of points above a grid in the x-y plane, using straight
lines to connect adjacent points. The mesh and surf plotting functions display surfaces in three dimensions. 28
mesh(X,Y,F) surf(X,Y,F)

Graph of the function F(X,Y)=X+Y

29
Example:
Plot the function 𝑓 𝑥, 𝑦 = 𝑥 2 + 𝑦 2 over the range −1 ≤ 𝑥 ≤ 1, −1 ≤ 𝑦 ≤ 1.

30
mesh produces wireframe surfaces that color only the lines connecting the defining points. surf displays both the
connecting lines and the faces of the surface in color.

mesh(X,Y,F) surf(X,Y,F)

Graph of the function F(X,Y)=X+Y 31


By default, MATLAB colors the mesh using the current colormap.

However, the command mesh(X,Y,F,'EdgeColor','black') uses a single-colored mesh by specifying the EdgeColor
surface property. In this exapmle black edge color.

Default MATLAB edge colors Black edge colors

32
Note:
You can create a mesh with see-through faces by disabling hidden line removal using the Matlab command hidden off

hidden on hidden off

33
Recall that surface plot (surf) is similar to a mesh plot (mesh) except that MATLAB colors the rectangular
faces of the surface.
The color of each faces is determined by the values of Z and the colormap (a colormap is an ordered list of
colors). The command colorbar add a color bar to show the mapping of data to color.

The default colormap is PARULA. In this case, the


colorbar colors begin with dark purplish-blue and blue, range
through green and orange, and end with bright
yellow. parula is named after a bird, the tropical
parula, which has these colors.

colormap PARULA

34
Write the Matlab comand help colormap for more information on the available colormaps. For example, the
command
colormap hsv
specify the hsv type colormap.

An hsv colormap varies the hue component of the hue-saturation-value color model. The colors begin with red,
pass through yellow, green, cyan, blue, magenta, and return to red. The map is particularly useful for displaying
periodic functions.

colormap PARULA colormap hsv


35
Example:
Plot the functionn 𝑓 𝑥, 𝑦 = sin(𝑥) + sin(𝑦) over three periods using the hsv colormap

36
Transparent Surfaces
You can make the faces of a surface transparent to a varying degree using the command alpha(x), where x is a
values ranging from 0 (completely transparent) to 1 (not transparent).

alpha(0) alpha(0.2)

alpha(1) alpha(0.6)

37
VII. Images
Handle Graphics
Using the Handle
Whenever MATLAB creates a graphics object, it assigns an identifier (called a handle) to the object. You can use
this handle to access the object’s properties with the set and get functions. For example, the following statements
create a graph and return a handle to a lineseries object in h.

x = 1:10;
y = x.^3;
h = plot(x,y);

You can use the handle h to set the properties of the lineseries object. For example, you can set its Color property:
set(h,'Color','red’)
You can also specify properties when you call the plotting function.
h = plot(x,y,'Color','red');
When you query the lineseries properties,
get(h,'LineWidth')
MATLAB returns the answer:
ans =
0.5000
38
Example

(i) Plot the function 𝑦 𝑥 = 𝑥 3 for 1 ≤ 𝑥 ≤ 10 and create a handle h for its corresponding graph.
(ii) Obtain the different default Matlab properties of that handle.
(iii) Modify the handle’s propoerties as follow:
- Color: red,
- Line style: dashed
- Line width: 3
- Marker: circle
- Marker size: 12
- Marker face color: 95% red and 95% blue
- Marker edge color: blue

39
Most plotting functions return the handles of the objects that they create so you can modify the objects using the set
command.
For example, these statements :

h = plot(magic(5));
set(h,'Marker','s','MarkerFaceColor',’g’)

plot a five-by-five matrix (creating five lineseries, one per row) and then set the Marker property to a square and the
MarkerFaceColor property to green.

For example, create the following a plot and save the lineseries handles into h.

h = plot(magic(5));

Suppose you want to add different markers to each lineseries and color the marker’s face color the same color as the
lineseries.

40
41
Finding All Objects of a Certain Type
Because all objects have a Type property that identifies the type of object, you can find the handles of all
occurrences of a particular type of object. For example,

hndl = findobj('Type','patch’);

finds the handles of all patch objects. For a graph handle patch = line

Finding Objects with a Particular Property


You can specify multiple properties to narrow the search. For example,

hndl = findobj('Type','line','Color','r','LineStyle',':');

finds the handles of all red dotted lines.

Using findobj as an Argument


Because findobj returns the handles it finds, you can use it in place of the handle argument. For example,

set(findobj('Type','line','Color','red'),'LineStyle',':’)

finds all red lines and sets their line style to dotted.

Note: We can also use the following command


h = findobj('PropertyName',PropertyValue,'-logicaloperator', PropertyName',PropertyValue,...) 42
(i) Run the following code: (ii) Find and plot all garphs with red color.
clear (iii) Find and plot all graphs wich contain pentagram or hexagram
close all markers
clc (iv) Find and plot all garphs with [0.9290 0.6940 0.1250] color.

h = plot(magic(5));
prop_name(1) = {'Marker'};
prop_name(2) = {'MarkerFaceColor'};
prop_values(1,1) = {'s'};
prop_values(1,2) = {get(h(1),'Color')};
prop_values(2,1) = {'d'};
prop_values(2,2) = {get(h(2),'Color')};
prop_values(3,1) = {'o'};
prop_values(3,2) = {get(h(3),'Color')};
prop_values(4,1) = {'p'};
prop_values(4,2) = {get(h(4),'Color')};
prop_values(5,1) = {'h'};
prop_values(5,2) = {get(h(5),'Color')};
set(h,prop_name,prop_values)

43
VIII. Animations
Using drawnow
The principle of the ’’Erase Mode Method’’ is to continually erase and then redraw the objects on the screen,
making incremental changes with each redraw.

Using the Erase Mode property is appropriate for long sequences of simple plots where the change from frame to
frame is minimal.

Example: Simulate the Brownian motion of 300 particles inside a fluid following the steps given bellow.

(i) Define the number of particles n and calculate their positions (x,y) at time t=0 supposing that at t=0, x and y are
randomly uniformally distributed on the interval −0.5 , 0.5 .
(ii) Using size 18, plot the points in a square with sides at -2 and 2 and save the handle.
(iii) Now begin the animation. To do that, create an infinite while loop, which you can eventually exit by typing Ctrl+C.
Each time through the loop:
- add a small amount of normally distributed random noise dx to x and dy to y, where 𝜂𝑑𝑥 = 𝜂𝑑𝑦 = 0 and
𝜎𝑑𝑥 = 𝜎𝑑𝑦 = 0.02 to the coordinates of the points.
- Then, instead of creating an entirely new plot, simply change the XData and YData properties of the original plot.
- Plot the new position of the particles using the command drawnow.

44
Using Movies (getframe and movie commands)

If you increase the number of points in the Brownian motion example to n = 300, it becomes more effective to save
a predetermined number of frames as bitmaps and to play them back as a movie.

First, decide on the number of frames, Generate the movie and use getframe to capture each frame.
nframes = 500; for k = 1:nframes
x = x + s*randn(n,1);
Next, set up the first plot as before. y = y + s*randn(n,1);
set(h,'XData',x,'YData',y)
n = 300; M(k) = getframe;
s = .02; end
x = rand(n,1)-0.5;
y = rand(n,1)-0.5; Finally, play the movie 30 times.
h = plot(x,y,'.');
set(h,'MarkerSize',18); movie(M,30)
axis([-2 2 -2 2])
axis square
45

You might also like