# 5. PLOTS in MATLAB

Objective: To give basic idea of plotting in Matlab with Data and equations in 2D & 3DPlots (Line, Scatter, Bar etc.,),. exploring Plot Features, Plot editing, and tricks to present plots in best way while documentation writing.

## 5.1. Introduction to MATLAB plots

MATLAB include standard plots with linear axes, plots with logarithmic and semi-logarithmic axes, bar and stair plots, polar plots, three- dimensional contour surface and mesh plots, and many more.

The line type (solid, dashed, etc.), color, and thickness can be prescribed, line markers and grid lines can be added, as well as titles, legend and text comment. Several graphs can be plotted in same plot and several plots can be placed on the same page.

## 5.2. Visualization

MATLAB has a powerful plotting engine that can generate a wide variety of 2 D and 3D plots.

## 5.3. Generating Data for 2D Plotting

MATLAB does not understand functions; it can only use arrays of numbers of *“equal length”*. We are using following x, y variables for plotting.

$$x=0\rightarrow 2\pi$$

$$y=sin(x)$$

## 5.3.1. Using Plot command

Now in Matlab command window or editor window write the above equations or just copy following lines and paste in the command window

*x=0:pi/100:2*pi; % Generating x array from 0 to $$2\pi$$ in increments of $$\pi/100$$*

* y=sin(x);*

* plot(x,y)*

We get the plot below as shown in Fig. 5.1.

Fig. 5.1. Matlab Plotting using ‘plot’ command.

## 5.3.1. From Plots in Matlab Main Window

In the Matlab main window, select the variables (using ctrl key) from workplace to be plotted and go to ‘PLOTS’ and choose required plot format and click, then you will see the following Fig. 5.2.

Fig. 5.2. Matlab plot from Workspace.

*Note: You will get error, if the lengths of the arrays are mismatch*

In general, the structure of the plot with title, x-y label, legend, marker and text are given in Fig. 5.3.

* Source: MATLAB- An introduction with applications-Amos Gilat*

Fig. 5.3. General structure of the plot.

### 5.5. Labels, Title and Legend

To add labels to the x and y axes, we can use the xlabel and ylabel commands -xlabel(‘x’), ylabel(‘y = sin(x)’)

To add a title, use the title command- title(‘plot of x vs sin(x))

To add a legend, use the legend command -legend (‘x’)

*x = 0:pi/100:2*pi;*

*xn = 0:pi/100:4*pi;*

*y = sin(x);*

*plot(x, y)*

*xlabel(‘x’), *

*ylabel(‘y = sin(x)’)*

*title(‘plot of x Vs sin(x)’)*

*legend(‘x’) *

*Note: legend can rearrange position by holding legend and dragging to convenient place in the plot or using legend(‘x’,number ). number =-1 (outside axis on right side) , 0 (inside axis),1 (upper right corner), 2 (upper left corner), 3 (lower left corner), 4 (lower right corner).*

### 5.4. Line specifications or specifiers

In general, all the plots were done in the Matlab default color is blue and line length is 0.5 units. If you have multiple plots to be compared in single Matlab window. Then we need different option to distinguish between all the different plots.

So, all the features can be changed by selecting a different option within the plot command. Now we have to added color, line style and markers to the data. We can also modify line width, marker edge and fill color and marker size.

The line colors defined in Matlab are r= red, g= green, b-blue, c=cyan, w=white , k=black, y=yellow and m=magenta.

Line style is default is solid (-), other formats are dash (–), dot(:), dash-dot (-.)and non (invisible).

Line width by default is 0.5, but you can increase up to 12.

Marker is by default non, but you can use plus(+),circle(o),asterisk(*), point(.), triangle up (^), triangle down (v), triangle left (<), triangle tight (>), square (s) , diamond (d), 5 pointed star ( p), 6 p0inted star (h).

*Note: Line specifiers are used in ‘plot’ command, all three together in any order.
*

*Note: Controlling the width, style of title, labels, line etc.,*

*Note: Generating different line colors in the same plot. Some times the number of lines are more than 8, and are distinguishable.*

Method 1:

dc=hsv(18); % 18 colours are generated

x = 0:pi/100:2*pi;

hold on % you much write this before the plot

i=1;

for d=0:0.2:2, % 11 lines in plot are taken

plot(x,sin(x-d),’color’,dc(i,:),’linewidth’,2)

i=i+1;

end

[1 1 0] Yellow

[0 0 0] Black

[0 0 1] Blue

[0 1 0] Bright green

[0 1 1] Cyan

[1 0 0] Bright red

[1 0 1] Pink

[1 1 1] White

[0.9412 0.4706 0] Orange

[0.251 0 0.502] Purple

[0.502 0.251 0] Brown

[0 0.251 0] Dark green

[0.502 0.502 0.502] Gray

[0.502 0.502 1] Light purple

[0 0.502 0.502] Turquoise

[0.502 0 0] Burgundy

[1 0.502 0.502] Peach

## 5.7. Axis commands

We can alter the displayed range and other parameters of the plot by using the axis command.

*Note: This is useful when you want o show plot only in particular range of data.*

Axis([xmin xmax ymin ymax])

Axis equal;

Axis square;

### 5.7.1. Axes Control

plot(x, y, x, y2, x, y3)

axis([0 2*pi –1 1])

grid on

xlim

ylim

### MATLAB symbols

% red line

Plot(t,a,’r’);

Hold on;

% black line

Plot(t,b,’k’);

% green dots

Plot(t,c,’g.’);

% cyan x’s

Plot(t,d,’cx’)

% dashed magenta % line with o’s

Plot(t,e,’–om’)

$$a=2t^2$$

$$b=sin(2\pi t)$$

$$c=e^{-15t}$$

$$d=cos(8\pi t)$$

$$e=2t^3-4t^2+t+1$$

Assume simulation time (or *t* is varying ) from 0 to 50 sec.

*Note: Copy following code and paste in MATLAB command window or editor window .*

clc

clear all

t=0:0.01:50; % Time* t* is starting from 0 to 50 in increments of 0.01

a=2*t.^2;

b=sin(2*pi*t);

c=exp(-15*t); % Exponential command is exp( )

d=cos(8*pi*t);

e=2*t.^3-4*t.^2+t+1;

Generate above data in MATLAB command window and execute other plots given below over specific range of 0:0.01:50

### 5.3.1. Using Plot Command

The simple command to plot in Matlab is ‘plot(x,y)’ and type plot(t, b) in command window and you will get the following Fig. 5.1

>>plot(t,b)

Fig.5.1

### 5.3.1. Using Plot Command

## 5.4. Plotting Multiple Graphs in the same plot

If you have multiple equations or data set and you want to plot in single Matlab plot window. The following are different methods to plot multiple grahps (lines or data) in single Matlab window.

### 5.4.1. Using the plot command

Here two or more graphs can be created in the same plot.

For example plot(x, y, u, v, t, h) which creates three graphs: y vs x, v vs u and h vs t, all in same plot.

And the vectors of each pair must be of same length.

Eg: plot(x, y, ‘b’, u, v, ‘- -r’, t, h, ‘g:’)

### 5.4.2. Using Hold on Command

Check: Plot a and then plot b, What do you observe? Only b , Why?

MATLAB will replace the current plot with any new one unless you specifically tell it not to

To have both plots on one figure use the hold on command

To make multiple plots use the figure command

Hold On / Hold Off

Hold on command only needs to be issued once per figure, thus calling hold on will result in all subsequent plot commands going to one figure unless a new figure command is issued or hold off is used.

Using the hold on, hold off Commands

Here one graph is plotted first with the plot command and then the hold on command is typed which keeps the figure window open to add additional graphs. Each plot command creates a graph that is added to the figure.

The hold off command stops this process.

### 5.4.3. Using the line Command

With the line command additional graphs(lines) can be added to a plot that already exits.

The form of the line command is:

line(x, y, ‘PropertyName’, PropertyValue)

line( x, y, ‘linestyle’, ‘- -’, ‘color’, ‘r’, ‘marker’, ‘o’)

Note: The major difference between the plot and the line commands is that the plot command starts a new plot every time it is executed, while the line command adds lines to a plot that already exist.

Note:

## 5.8. Error Bars

In addition to markers, MATLAB can generate error bars for each datapoint using the errorbar command

errorbar(x,y,e) or errorbar(x,y,ll,lu);

Will generate line plus error bars at y+/-e or (y-ll,y+lu)

## 5.9. Subplot command

So far we have only been generating individual plots. MATLAB can also generate a matrix of plots using the subplot command

## 5.10. Multiple Plots

plot(x, y, ‘r’)

figure

plot(x, y, ‘b’)

figure(1)

plot(x, y, ‘g’)

Practice

Generate a 3×1 array of figures, each with a title

Axis range of plots 1 and 2 should be 0 to 1 on x and y

Plot 1 should include function a and b (color code)

Plot 2 should include c and d (color code)

Plot 3 should include f with error bars of your liking

Practice

More examples

x = -pi:pi/10:pi;

y = tan(sin(x)) – sin(tan(x));

plot(x,y,’–rs’,’LineWidth’,2,…

‘MarkerEdgeColor’,’k’,…

‘MarkerFaceColor’,’g’,…

‘MarkerSize’,10)

x = -pi:.1:pi;

y = sin(x);

plot(x,y)

set(gca,’XTick’,-pi:pi/2:pi)

set(gca,’XTickLabel’,{‘-pi’,’-pi/2′,’0′,’pi/2′,’pi’})

xlabel(‘-\pi \leq \Theta \leq \pi’)

ylabel(‘sin(\Theta)’)

title(‘Plot of sin(\Theta)’)

text(-pi/4,sin(-pi/4),’\leftarrow sin(-\pi\div4)’,…

‘HorizontalAlignment’,’left’)

## 5.11. Other Plots

plot – Graph 2-D data with linear scales for both axes

loglog – Graph with logarithmic scales for both axes

semilogx – Graph with a logarithmic scale for the x-axis and a linear scale for the y-axis

semilogy – Graph with a logarithmic scale for the y-axis and a linear scale for the x-axis

plotyy – Graph with y-tick labels on the left and right side

## 5.12. Labels and Titles

x = -pi:pi/100:pi;

y = sin(x);

plot(x,y)

axis([-pi pi -1 1])

ylabel(‘sin(x)’)

xlabel(‘-\pi \leq {\itx} \leq \pi’)

title(‘\fontsize{16}Graph of the sine function’)

text(1,-1/3,’\bf{Note the odd symmetry.}’)

Get Properties

Finding handles:

gcf – get current figure handle

gca – get current axes handle

5.13. Getting properties

get(h) – all properties of the graphics object identified by the handle h.

get(h, ‘PName’) – get the value of the property ‘PName’ of the graphics object identified by h.

Set Properties

Setting properties :

set(h, ’PName’, PValue, …) – sets the named properties to the specified values on the object(s) identified by the handle(s).

For example :

x = -pi:.1:pi;

y = sin(x);

plot(x, y)

set(gca, ‘XTick’, -pi:pi/2:pi)

set(gca, ‘XTickLabel’, {‘-pi’,’-pi/2′,’0′,’pi/2′,’pi’})

## 5.14. Other plots

### 5.14.1. Bar Charts

y = round(rand(5,3)*10);

subplot(2 , 2, 1)

bar(y, ‘group’)

title ‘Group’

subplot(2, 2, 2)

bar(y, ‘stack’)

title ‘Stack’

subplot(2, 2, 3)

barh(y, ‘stack’)

title ‘Stack’

subplot(2, 2, 4)

bar(y,1.5)

title ‘Width = 1.5’

5.14.2. Pie Chart

val = [12 17 21];

explode = [0 0 1];

h = pie(val, explode);

colormap summer

textObjs = findobj(h, ‘Type’, ‘text’);

newStr = {‘X’; ‘Y’; ‘Z’};

set(textObjs, {‘String’}, newStr)

5.14.3. Histogram

Y = randn(10000,3);

hist(Y)

5.14.4. Contour and Quiver

n = -2.0:.2:2.0;

[X,Y,Z] = peaks(n);

[C, h] = contour(X,Y,Z,10);

Colormap(‘default’);

clabel(C,h)

[U,V] = gradient(Z,.2);

hold on

quiver(X,Y,U,V)

hold off

5.14.5. Mesh

[U, V] = meshgrid(-8:.5:8);

R = sqrt(U.^2 + V.^2) + eps;

H = sin(R)./R;

mesh(H)

### 5.14.6. Surf

surf(X, Y, Z, ‘FaceColor’, ‘interp’, …

‘EdgeColor’, ‘none’, … ‘FaceLighting’, ‘phong’)

axis tight

view(-50,30)

camlight left

### 5.14.7. Movies

Z = peaks;

surf(Z);

axis tight

set(gca, ‘nextplot’, ‘replacechildren’);

% Record the movie

for j = 1:20

surf(sin(2*pi*j/20)*Z, Z)

M(j) = getframe;

end

% Play the movie twenty times

movie(M,20)

## 5.15. Saving Figures

From menu:

File Save – MATLAB format

File Export – Other graphics formats

From command line:

Saveas(gcf, filename, extension)

## 5.16. Print

5.17. Three-Dimensional Plots

5.17.1. Introduction

Three- dimensional (3-D) plots can be a useful way to present data consists of more than two variables.

They include line and wire, surface, mesh plots, and many others.

The plots can also be formatted to have a specific appearance and special effects.

5.1.1. Line plots

A three- dimensional line plot is a line that is obtained by connecting points in a three dimensional space.

A basic 3-D plot is created with the plot3 command.

plot3(x, y, z, ‘ line specifiers ’, ‘PropertyName’, property value)

If x, y, and z are three vectors of the same length,

plot3(x, y z) generates a line in 3-D through the points whose coordinates are the elements of x, y, and z and then produces a 2-D projection of that line on the screen.

For example, these statements produce a helix.

t = 0:pi/50:10*pi;

plot3(sin(t),cos(t),t)

axis square; grid on

clc

t=0:.1:6*pi;

x=sqrt(t).*sin(2*t);

y=sqrt(t).*cos(2*t);

=0.5*t;

z=0.5*t;

plot3(x,y,z,’k’,’linewidth’,2)

grid on

xlabel(‘x’)

ylabel(‘y’)

zlabel(‘z’)

5.1. Mesh and Surface plots

Mesh and surface plots are three-Dimensional plots that are used for plotting functions of the form

z= f(x, y) where x and y are the independent variables and z is the dependent variable.

Steps involved: i)Create a grid in the x-y plane, ii) calculate the value of z at each point iii)create plot

MATLAB has a built in function called meshgrid, that can be used for creating the X and Y matrices.

The form of the meshgrid function is:

[X, Y] = meshgrid(x, y)

This example evaluates and graphs the two-dimensional sinc function, sin(r)/r, between the x and y directions. R is the distance from the origin, which is at the center of the matrix.

[X,Y] = meshgrid(-8:.5:8);

R = sqrt(X.^2 + Y.^2) + eps;

Z = sin(R)./R;

mesh(X,Y,Z,’EdgeColor’,’black’)

[U, V] = meshgrid(-8:.5:8);

R = sqrt(U.^2 + V.^2) + eps;

H = sin(R)./R;

mesh(H)

Additional information on mesh

5.1.1. Change in color

C=[ 0 0 0] black; [1 0 0] red; [0 1 0] green

[0 0 1] blue; [1 1 0] yellow ;[1 0 1] magenta; [.5.5 .5] gray

[RGB] – red green blue 0- min; 1- max intensity

Colormap(c)

Grid on /grid off

Box on/ box off

5.1.2. Making mesh and surface plots

A surface plot is similar to a mesh plot 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). These statements graph the sinc function as a surface plot, specify a colormap, and add a color bar to show the mapping of data to color:

Eg:

surf(X,Y,Z)

colormap hsv

colorbar

Examples:

Produce a combination mesh and contour plot of the peaks surface:

[X,Y] = meshgrid(-3:.125:3);

Z = peaks(X,Y);

meshc(X,Y,Z);

axis([-3 3 -3 3 -10 5])

To Generate the curtain plot for the peaks function:

[X,Y] = meshgrid(-3:0.125:3);

Z = peaks(X,Y);

meshz(X,Y,Z)

Displays a surface plot and contour plot of the peaks surface.

Eg:

[X,Y,Z] = peaks(30);

surfc(X,Y,Z)

colormap hsv

axis([-3 3 -3 3 -10 5])

5.1.3. Plots with special graphics

MATLAB has additional functions for creating various types of special three dimensional plots.

Plot of Sphere:

Syntax:

sphere

sphere(n)

[X,Y,Z] = sphere(…)

Eg: sphere

axis equal

Plot of cylinder:

Syntax:

[X,Y,Z] = cylinder(r)

[X,Y,Z] = cylinder(r,n)

cylinder(axes_handle,…)

cylinder(…)

Eg: cylinder

axis square

h = findobj(‘Type’,’surface’);

set(h,’CData’,rand(size(get(h,’CData’))))

3-D Bar Plot:

Syntax:

bar3(Y)

bar3(x,Y)

bar3(…,width)

Eg: Y= [1 6.5 7; 2 6 7; 3 5.5 7; 4 5 7; 3 4 7; 2 3 7; 1 2 7];

bar3(Y)

3- D Stem Plot

Draws sequential points with markers and vertical lines from the x-y plane

Syntax:

stem3(X,Y,Z)

Eg:

X = linspace(0,1,10);

Y = X./2;

Z = sin(X) + cos(Y);

stem3(X,Y,Z,’fill’)

view(-25,30)

3- D Scatter plot

Syntax:

Scatter3(X, Y, Z)

Eg:

t=0:0.4:10;

x=t;

y=sin(t);

z=t.^1.5;

scatter3(x,y,z,’filled’)

grid on

colormap([0.1 0.1 0.1])

xlabel(‘x’); ylabel(‘y’)

zlabel(‘z’)

3-D Pie Plot

Syntax:

Pie3(X,explode)

Eg:

x = [1 3 0.5 2.5 2];

explode = [0 1 0 0 0];

pie3(x,explode)

colormap hsv

The view Command

The view command controls the direction from which the plot is viewed.

This is done by specifying a direction in terms of azimuth and elevation angles or by defining a point in space from which the plot is viewed.

view(az,e1) or view([az,e1])

az is azimuth, which is an angle (in degrees) in the x-y plane measured relative to the negative y axis direction and is defined in the counter-clockwise direction.

e1 is the angle of elevation(in degrees) from the x-y plane. A positive value corresponds to opening an angle in the direction of the z-axis.

Examples of Views Specified with Azimuth and Elevation

For example, these statements create a 3-D surface plot and display it in the default 3-D view.

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

Z = X.*exp(-X.^2 -Y.^2);

surf(X,Y,Z)

The statement view([180 0]) sets the viewpoint so you are looking in the negative y-direction with your eye at the z = 0 elevation.

1. Camera Toolbar

This picture illustrates how the camera is defined in the terms of properties of the axes

• Camera Motion Controls – these tools select which camera motion function to enable. You can also access the camera Motion controls from the tools menu.

• Principal Axis Selector – some camera controls operate with respect to a particular axis. These selectors enable you to select

• The principal axis or to select non-axis constrained motion. The selectors are grayed out when not applicable to the currently selected function. You can also access the principal axis selector from the tools menu.

Problems

The displacement of an object falling under the force of gravity is given by:

where g is the acceleration of gravity [m/s2], y is the distance traveled [m], and t is time [s].

The following table gives the values of g for three different planets:

Planet g

Earth 9.80 m/s2

Jupiter 24.79 m/s2

Mercury 3.72 m/s2

PART 1

Plot the distance fallen as a function of time near the surface of the Earth between 0 and 10 seconds, with an increment of 1 second. Add a title and x and y labels.

SOLUTION

>> % Define time values

>> t = 0:1:10;

>> % Define acceleration of gravity

>> g = 9.80;

>> % Compute displacement y

>> y = g * t.^2;

>> % Plot

>> plot(t,y,’b–‘)

>> % Create labels

>> grid on

>> xlabel(‘Time [s]’)

>> ylabel(‘Distance fallen [m]’)

>> title(‘Distance fallen as a function of time on Earth’)

Hint: You can define the color and the style of a curve when using the plot command. In the example below, ‘b- -‘ stands for blue dashed line. Other possible options are “:” for a dotted line, “-.” for a dash-dotted line, “-“ for a solid line. The colors are designated by the first letter of the desired color (b,r,g,y… k = black). If the style or the color is not specified, MATLAB uses its default settings. See help plot for additional information.

Hint: You can zoom in and out, draw arrows, add titles, labels, legends, or write text directly in the figure using the menu bar.

YOUR TURN

Repeat the same exercise for Mercury.

PART 2

Multiple functions can be plotted on the same figure using the hold on and hold off commands. Plot the displacement curve for both the Earth and Jupiter in the same figure and add a legend.

SOLUTION

>> % Compute displacement for Earth

>> g = 9.80;

>> t = 0:1:10;

>> y = g * t.^2;

>> % Plot displacement for Earth

>> plot(t,y,’b–‘)

>> grid on

>> hold on

>> % Both functions are plotted in the same figure

>> % Compute displacement for Jupiter

>> g = 24.79;

>> y = g * t.^2;

>> % Plot displacement for Jupiter

>> plot(t,y,’r-‘)

>> % Create labels

>> title(‘Distance fallen as a function of time’)

>> xlabel(‘Time [s]’)

>> ylabel(‘Distance fallen [m]’)

>> % Add a legend

>> legend(‘Earth’,’Jupiter’)

>> % End of the hold command

>> hold off

YOUR TURN

Plot all three curves for the three planets in the same figure. Use different styles for each of the planets and include a legen

PART 3

The three curves can also be plotted on the same figure in three different plots using the subplot command. Plot the curves for Earth and Jupiter using subplot.

SOLUTION

>> % Compute displacement for Earth

>> t = 0:1:10;

>> g = 9.80;

>> y = g*t.^2;

>> % Plot

>> subplot (2,1,1)

>> plot (t,y,’b–‘)

>> xlabel (‘Time [s]’)

>> ylabel (‘Distance fallen [m]’)

>> title (‘Distance fallen as a function of time on Earth’)

>> grid on

>> % Define displacement for Jupiter

>> g=24.79;

>> y = g*t.^2;

>> % Plot

>> subplot(2,1,2)

>> plot(t,y,’r-‘)

>> xlabel(‘Time [s]’)

>> ylabel(‘Distance fallen [m]’)

>> title(‘Distance fallen as a function of time on Jupiter’)

>> grid on

YOUR TURN

Using subplot, create three different displacement plots in the same window corresponding to each of the three planets.