Call Us On : +91 9873543020    [email protected]

## MATLAB plots

##### Welcome to the series of blogs on Digital Image Processing using MATLAB. If you are looking for complete guidance in understanding the concepts of the digital images and image processing using MATLAB, you’re at the right place! In this series, we will discuss the concepts of Image Processing along with the implementation from scratch to the advanced level.  In this section- MATLAB plots, we will discuss plotting in MATLAB in detail.

A ‘picture’ is worth a thousand words! In the field of technical analysis, ‘graphs’ are of the same worth. MATLAB offers a variety of plotting options for graphs and images. You can draw both two and three-dimensional plots in MATLAB. Let’s start with the 2D plot.

### The plot command

The plot() command is used for 2D plots. You need two vectors of the same length for plotting a two-dimensional graph. The simplest form of the plot command is,

plot(x,y)

where x and y are the vectors of the same length.
Let’s plot the curve- y = x2 for illustration. Here x is the independent variable and y is the dependent variable. When you think of a plotting a curve, the first thing to consider is the range of the dependent variable. Obviously, the range of the dependent variable will depend on the independent variable and the nature of the expression.

The second important thing to realize is that you are plotting a curve on a computer that is discrete. Therefore, you have to generate the variable x in discrete form. We have discussed the generation of vectors with equally spaced elements in the earlier section. You can go through it here under the heading of ‘Creating special arrays with constant spacings’.

Let’s create a vector x in the range [0,10] with 5 elements. We use the linspace command here as the first & last elements and the number of elements are known.

x = linspace(0,10,5);

You can see the values in x in the workspace or the command window. The variable y is simple to create.

y = x.^2

Now you are ready with both the variables x and y. Let’s plot the curve!

plot(x,y)

So finally you’ve got the plot!

#### Not so perfect?

You might not be impressed with the plot because of the following reasons:

1. The plot does not seem to be smooth enough.
2. No markers are used for denoting the curve points.
3. There is no additional information like axes labels, plot titles, legends, etc.

Don’t worry! we will address these issues step by step. The first problem is due to the smaller number of data points. A large number of points lead to a smoother curve. For example, let’s have 20 points for the x and the corresponding y.

x = linspace(0,10,20);
y = x.^2;

Now you’ll get a smoother curve with these variables. The remaining issues are related to the syntax and additional arguments of the plot command.

You can add markers to the plot by adding an argument – ‘ColMark’, where Col represents the color and Mark denotes the marker. For example.

plot(x,y,’ro’)

Here ‘ro’ means red color and o (circle) marker. You can use only markers also. In that case the default color will be used. The details about the plot command arguments (list of colors, markers, and the line types) can be found here.

#### what if a figure window is already open?

Before we get the plot by executing the above command, let’s discuss an important point relating to the figure windows.

When you use plot command for the first time (with no figure window open), a figure window pops up showing the plot. But if you run the command again, the new plot will replace the previous one in the same window. To avoid this, you should use the command ‘figure’ before the plot command. For example,

figure, plot(x,y,'ro')

The above command will add markers but not the lines joining them. To show the markers as well as the lines, you need to write ‘r-o’. r for red color, – for lines joining the points and o for the markers.

x = linspace(0,10,20);
y = x.^2;
figure, plot(x,y,'r-o')

You’ll get the following plot after running the commands.

So two issues have been resolved now. The graph is relatively smoother and the markers are included.

#### How to add axis labels and the title?

You can add axis labels using the following commands for x and y axes.

xlabel('x -->')
ylabel('y -->')

Here xlabel and ylabel are the commands for labeling the x and the y-axes. And the text within the single quotes is the label you wish to print on the axes.

The title of the graph is added using the following command.

title('plot of the curve y = x^2')

So finally, putting all the commands together for plotting the curve y = x2.

clc           % clear the command window screen
clear         % clear all the variable in the workspace
close all     % close all the previous figures

x = linspace(-10,10,40);  % take x values from -10 to 10 with 40 points
y = x.^2;         % create variable y
figure,
plot(x,y,'r-o')   % plot command
xlabel('x -->')   % add x-axis label
ylabel('y -->')   % add y-axis label
title('plot of the curve y = x^2') % add title of the plot


The command close() is used for closing the figure windows. MATLAB figure windows have figure numbers. So if you wish to close figure 2, you should write the command close(2). However, if you wish to close all the previous figures, you should write the command- close all or close(‘all’). The figure, command at line 7 is optional here as the previous figures are already closed. So the final plot looks like follows.

If you wish to add markers with different color, use an additional argument in the plot command as follows.

plot(x,y,'r-o','markeredgecolor','b')  % the marker color is blue

plot(x,y,'r-o','markeredgecolor','b','markerfacecolor','b')  % the marker edge and face color is blue

#### How to plot multiple graphs in the same figure?

Showing more than one plot in the same figure is easy. You can do it in two ways. One is adding the new variables in the single plot command. For example, suppose you wish to plot a straight line z = 3x + 50 on the existing figure. So first you have to create the variable z.

z = 3*x + 50;

And then in the plot command, you need to add the new x and y-axes variables (which are x and z in this case).

plot(x,y,'r-o',x,z,'b-')

Notice that the input arguments for the first curve are x,y and ‘r-o’. The same for the second curve are x,y and ‘b-‘. The marker is not added for the second plot deliberately. The set of arguments for both the curves are separated by a comma. You can add as many plots as you want. The resulting plot is,

The second way of plotting multiple curves on a single figure is using the command ‘hold on’. You write the plot command for the first curve as before. Put the hold on command next and then write a new plot command for the new curve. For example,

plot(x,y,'r-o')
hold on
plot(x,z,'b-')

The plot will be the same using both methods.

#### How to add legends in the plot?

You can add legends to annotate the curves in the figure using the ‘legend’ command.

legend('curve1','curve2',...,'curveN')

The legend order is according to the order of the plot. So the command for the current example would be,

legend('y = x^2','z = 3x + 50')

The output figure with legends is as follows.

#### Setting the axis limits

You can set the axes limits using the following command.

axis([xmin xmax ymin ymax])

where xmin & xmax are the minimum & maximum limits of the x-axis and ymin & ymax are that of the y-axis. If only one axis is to be set, use one of the following commands.

xlim([xmin xmax])
ylim([ymin ymax])

### Subplots (multiple figures within one window)

Sometimes we need to show two or more figures within a single window. We use the ‘subplot’ command for this. It draws a grid of figures within one window. The general syntax for subplot is,

subplot(rows,columns,plot_num)

Here rows and columns denote the dimension of the plot grid. plot_num is the current plot number counted row-wise. For example, let’s draw four different plots of different curves.

clc
clear
close all
x = -pi:0.1:pi; % vector of equally spaced elements between -pi to pi, with spacing of 0.01.
y1 = x.^2;
y2 = sin(x);
y3 = cos(x);
y4 = x.^3;

figure,
subplot(2,2,1)          % First subplot
plot(x,y1,'r-')         % red solid line
title('y = x^2')

subplot(2,2,2)          % Second subplot
plot(x,y2,'b-*')        % blue solid line with * marker
title('y = sin(x)')

subplot(2,2,3)          % Third subplot
plot(x,y3,'g--')        % green dashed line
title('y = cos(x)')

subplot(2,2,4)          % Fourth subplot
plot(x,y3,'k-.')        % black dash-dot line
title('y = x^3')

suptitle('subplot example')  % super(main) title

The resulting plot is,

### 3D plots

When the data consist of more than two variables, we require 3D plots. Different commands are used for plotting different kinds of 3D objects (eg. line, surface).

#### The plot3 command

plot3 is used for plotting 3D points or 3D lines. The basic syntax for plot3 is

plot3(X, Y, Z)

where X, Y, and Z are the set of coordinates of the points joining the 3D line. The additional arguments (line type, markers, color, etc.) is the same as for the 2D plot.

So first we have to get these vectors according to the 3D line and then use the plot3 command. For example, let’s try to plot a 3D helix. The equations and the plotting command would be as follows.

z = 0:pi/50:10*pi;
x = sin(z);
y = cos(z);
figure,
plot3(x,y,z,'r')

And the plot generated is

You should try plotting different 3D lines with different equations.

#### The mesh and surf command

These commands are used for plotting the surfaces that are produced using the equation z = f (x,y). Here x and y are the independent variables and z is the dependent variable. That is, for different combinations of x and y, you’ll get the different values of z. So you have to create a grid of all possible values of (x,y) within their domain, before plotting the 3D surface. We call this grid as mesh grid. Therefore, plotting a 3D surface using mesh or surf command requires the following three steps.

• Create a grid of the independent variables (x,y) within their domain.
• Obtain the value of the dependent variable (z) at each of the grid points.
• Plot the 3D surface using mesh or surf command

We take the example of plotting a surface defined by the following equation.

z = 1.8^{-1.5\sqrt{x^2+y^2}}\sin{x}\cos{0.5x}

over the domain -3≤x≤3 and -3≤y≤3.

So the first task is to generate a grid of x and y in the given range. To create a grid, MATLAB has a command namely meshgrid. The grids for the current example is generated as follows.

x = -3:0.25:3      % descrete values of x between -3 and 3 with the spacing of 0.25
y = -3:0.25:3      % descrete values of y between -3 and 3 with the spacing of 0.25
[X,Y] = meshgrid(x,y);  % create grid using meshgrid

The output X and Y from the meshgrid are the matrices that together constitute the all possible combinations of x and y values. Next, we implement the equation.

Z = 1.8.^(-1.5*sqrt(X.^2 + Y.^2)).*sin(X).*cos(0.5*Y);

Note that here element-wise operation is used for generating the values of Z. Finally, plot the surface Z using both the commands -mesh and surf.

figure,
subplot(1,2,1)
mesh(X,Y,Z)
title('3D plot using mesh')

subplot(1,2,2)
surf(X,Y,Z)
title('3D plot using surf')

The simulation result is as follows.

Observe the visual difference between the mesh and the surf plots. You should try different 3D plots using these commands.

#### More commands for 3D plotting

There are a few variants of the mesh and the surf commands with some additional features. Some of them are –

• meshz: to draw a curtain around the mesh
• meshc: to draw the contour plot beneath the mesh
• surfc: to draw the contour plot beneath the surface
• surfl: to draw the surface plot with lighting
• contour3: to draw the 3D contour plot
• contour: to draw the projections of the contour in the xy plane

I would recommend you to use these commands for the interesting visualization of 3D plots.

Ok, so in this tutorial, we have got a comprehensive idea of the MATLAB plots in great detail. In the next tutorial, we will discuss the syntax and implementation of MATLAB functions with examples.

Thank you.

Contact us!

For training, Research Assistance, and Consultancy Services on Computer Vision, Deep Learning, Signal Processing, Image Processing, and Medical Signal/Image Processing.