Plots Matlab

Subplots and Overlay Plots

Plots are useful in providing information in picture view and MATLAB provides the facility for creating a plot using plot command. Hold on retains plots in the current axes so that new plots added to the axes do not delete existing plots. New plots use the next colors and line styles based on the ColorOrder and LineStyleOrder properties of the axes. MATLAB ® adjusts axes limits, tick marks, and tick.

MATLAB can create figures that contain an array of plots, called subplots. These
are useful’ when you want to compare the same data plotted with different axis
types, for example. The MATI…ABsubplot command creates such figures.
We frequently need to plot more than one curve or data set on a single plot.
Such a plot is called an overlay plot. This section describes several MATLAB
commands for creating o.verlayplots.
Subplots
You-can use the subplot command to obtain several smaller “subplots” in
the same figure. The syntax is subplot (rn , n, p). This command divides the
Figure window into an array of rectangular panes with m rows and n columns. The
variable p tells MATLAB to place the output of the plot command following
the subplot command into ‘the ptij, pane. For example, subplot (3,2, 5)
creates an array of six panes, three panes deep and two panes across, and directs:
the next plot to appear in the fifth pane (in the bottom-left comer). The following:
script file created Figure 5.2-1, which shows the plots of the functions y =
e-l.2x sin(10x +5) for 0 ~ x ~ 5 and y = Ix3 – 1001for -6 ~ x ~ 6.
x = [0:0.01:5];
y = exp(-1.2*x}.*sin(10*x+5};
subplot(1,2,1}
plot(x,y},xlabel(‘x’},ylabel(‘y’),axis([O 5 -1 1])
x = [-6:0.01:6];
‘:;:”.
~:” ,

y = abs(x.A3-100);
subplot(1,2,2)
plot(x,y),xlabel(‘x’),ylabel(‘y’),axis([-6 60350])

Test Your Understanding
15.2-1 Pick a suitable spacing for t and v, and use the subplot command to
plot the function z = e-O.51 cos(20t – 6) for 0 ::: t :::8 and the function
u = 61oglO(V2 + 20) for -8 ::: v ::: 8. Label each axis

Overlay Plots
You can use the following variants of the MATLAB basic plotting functions
plot (x,y) and plot (yi to create overlay plots:
• plot (A) plots the columns of A versus their indices and generates
n curves where A is a matrix with m rows and n columns.
• plot (x,A) plots the matrix A versus the vector x,where x is either a row
vector or column vector and A is a matrix with m rows and n columns. If the
length of x is m, then each column of A is plotted versus the vector x. There
will be as many curves as there are columns of A. If x has length n, then.

each row of A is plotted versus the vector x. There will be as many curves
as there are rows of A.
• plot (A, x) plots the vector x versus the matrix A.If the length ofx is m,
then x is plotted versus the columns of A. There will be as many curves as
there are columns of A. If the length of x is n, then x is plotted versus the
rows of A. There will be as many curves as there are rows of A.
• plot (A, B) plots the columns of the matrix Bversus the columns of the
matrix A.

Data Markers and Line Types
Toplot the vector y versus the vector x and mark each point with a data marker, enclose
the symbol for the marker in single quotes in the p l o t function. Table 5.2-1
shows the symbols for some of the available data markers. For example, to use a
small circle, which is represented by the lowercase letter 0, type plot (x, y ,
‘0 ‘) . This notation results in a plot like the one on the left in Figure 5.2-2. To
connect each data marker with a straight line, we must plot the data twice, by
typing plot (x , y, x , y, ‘0’ ). See the plot on the right in Figure 5.2-2.
Suppose we have two cur~es or data sets stored in the vectors x, y, U, and v.
To plot y versus x and v versus U on the same plot, type plot (x, y , U, v) . Both
sets will be plotted with a solid line, which is the default line style. To distinguish
the sets, we can plot them with different line types. To plot y versus x with a
solid line and U versus v with a dashed line, type plot (x, Y, u , v, ‘ – – , ) ,
where the ‘symbols ‘ – .:» represent a dashed line. Table 5.2-1 gives the symbols
for other line types. To plot y versus x with asterisks (*) connected with a dotted
line, you must plot the data twice by typing plot (x, y, ,*, ,x, y, ‘ : ‘ ). See
Figure 5.2-3.
You can obtain symbols and lines of different colors by using the color
symbols shown in Table 5.2-1. The color symbol can be combined with the
data-marker symbol and the line-type symbol. For example, to plot y versus x
with green asterisks (*) connected with a red dashed line, you must plot the data
twice by typing plot (x, y, ‘g*’ ,x, y, ‘r–‘ ). (Do not use colors if you
are going to print the plot on a black-and-white printer.)

.Specifiers for data markers, line types, and colors

Data plotted using asterisks connected with a dotted line.

Labeling Curves and Data
When more than one curve or data set is plotted on a graph, we must distinguish
between them. If we use different data symbols or different line types, then we
must either provide a legend or place a label next to each curve. To create a legend,
use the legend command. The basic form of this command is legend
(,stringl’ ,string2′ ),where stringl and string2 are text strings
of your choice. The legend command automatically obtains from the plot
the line type used for each data set and displays a sample of this line type in the
legend box next to the string you selected. The following script file produced the
plot in Figure 5.2-4.
x = [0:0.01:2];
y sinh (x)i
z tanh (x)i
plot(x,y,x,z,’–‘),xlabel(‘~’),
ylabel(‘Hyperbolic Sine and Tangent’),
legend(‘sinh(x)’, ‘tanh(x)’)
The legend command must be placed somewhere after the plot command.
When the plot appears in the Figure window, use the mouse to position the legend
box. (Hold down the left button on a two-button mouse to move the box.)

Gridlines can obscure the legend box. To prevent this situation, instead of
placing the legend command as shown in the preceding session, type the
following lines in the Command window, after the plot appears in the Figure
window but before printing the plot:
»axes(legend(‘string1’, ‘string2’»
»refresh
The first line makes the legend box act as the current set of drawing axes. The
refresh command forces the plot to be redrawn in the Figure window. You
can then print the plot. The axes command, not to be confused with the axis
command, is a powerful command with man§’ features for manipulating figures
in MATLAB. However, this advanced topic is not covered in this text.
Another way to distinguish curves is to place a label next to each. The label can
bt! generated with either the gt ext command, which lets you place the label using
the mouse, or with the t ext command, which requires you to specify the coordinates
of the label. The syntax of the gt’ext command is gtext ( , string’ ),
where string is a text string that specifies the label of your choice. When this
command is executed, MATLAB waits for a mouse button or a key10 be pressed
while the mouse pointer is within the Figure window; the label is placed at that
position of the mouse pointer. You may use more than one gtext command for
a given plot. .’
The text command, text (x,y,’ string’), adds a text string to the
plot at the location specified by the coordinates x , y. These coordinates are in
the same units as the plot’s data. The following script file illustrates the uses
of the gtext and text commands and was used to create the plot shown in
Figure 5.2-5.
x [0:0.01:1);
y = tan(x);
z = see(x};
plot (x,y, x, z) ,xlabel (‘x’), ….
ylabel(‘Tangent and Seeant’),gtext(‘tan(x) ‘),
text (0.3,1.2, , see (xl’ )
Of course, finding the proper coordinates to use with the text command usually
requires some trial and error.

Graphical Solution of Equations
When we need to solve two equations in two unknown variables, we can plot
the equations. The solution corresponds to the intersection of the two lines. If
they do not intersect, there is no solution. If they intersect more than once, there
are multiple solutions. A limitation of this approach is that we must know the
approximate ranges of the two variables so that we can generate the plot. Another
limitation is that the accuracy of the solution is limited by the accuracy with which
we can read the plot. Of course, we can-always expand the plot to increase the
accuracy.

Figure S,.t:S Applica~ of the gtext and text comm~ds/

The hold Command
The hold command creates a plot that needs two or more plot commands.
Suppose we wanted to plot Y2 = 4 + e-x cos 6x versus YI = 3 + e-x sin 6x,
-I ~x ~ I on the same plot with z = (0.1 + 0.9i)”, where 0 ~ n ~ 10. This
plot requires two plot commands. The script file to create this plot using the ho 1d
command follows. ‘
x = [-1:0.01:1];
yl = 3+exp(-x) .*sin(6*x);
y2 = 4+exp(-x).*cos(6*x);
plot((0~1+0.9i).A[0:0.01:10]),hold,plot(y1,y2),
gtext(‘y2 versus y1’),gtext(‘Imag(z) versus Real(z)’)
Figure 5.2-8 shows the result.
Although it is not needed to generate multiple plots with the’
plot (x,y ,u , v) type command, the hold command is especially useful with
some of the advanced MATLAB toolbox commands that generate specialized
plots. Some of these commands do not allow for more than one curve to be generated
at a time, and so they must be executed more than once to generate multiple
curves. The hold command is used to do this.
, When more than one plot command is used, do not place any of the gte)S:t
commands before any plot command. Because the scaling changes as each
plot command is executed, the, label placed by the gtext command might

Bar

end up in the wrong position. ‘Table 5.2-2 summarizes.the plot enhancement
introduced in this section.

Test Your’ Understanding
‘·’1 ”
15.2-2 Plot the fOJ1owing two data sets on ~the~ame’ plot.’ Fo~ each set. x =
O. 1,2.3,4.5. Use ,a ‘different data marker for ..ea’tch. set. Connect the
markers for the first set with solid lines. Connect’ the, markers for the
second set with dashed lines: Use a legend, and iabel the plot axes appropriately.
‘The first set is y = 11. 13.8.7.5,9. The second set is y = 2.
415•.3,2;,4.
j’ . ..’ . I ‘I .f ~ 15.2-3 Plot y. = coshx and y = O~~ex on’ the same plot for 0 ~ x ~2. Use
different line types and a’legendto distinguish the curves. Label the’ plo
axes appropriately.
15,2-4 .Plot y =’ sinhx and y = O.5ex on the same plot for 0 ~ x ~ 2. Use a
solid line type for each, the gt ext command to label the sinh x ‘curve.
and the t ext command to label the O.5ex curve. Label the’ plot axes
-appropriately .
•- If;
1512-5, .Use the hold command and the plot command twice to plot y = sinx
, and y =x – x3/3 on the same plot for 0 ~ x ~ I. Use a solid line type
for each and use the gtext command to label each curve. Label the pi
axes appropriately .

Annotating Plots
You can create text, titles, and labels that contain mathematical symbols, Greek
letters, and other effects such as italics. The features are based on the TEXtypesetting
language. Here we give a summary of these features. For more information,
including a list of the available characters, search the online help for “text
properties.”
The text, gtext., title,xlabel, and ylabel commands all require
a string as their argument. For example, typing
»title(‘A*exp(-t/tau)sin(omega t)’)
produces a title that looks like A*exp (- t / tau f sin (omegat) but is supposed
to represent the function Ae-I/f sin(wt). You can create a title that looks
like the mathematical function by typing
<:»
»titie(‘Ae”{- t/tau}sin(’o,mega t)’)
The backslash character precedes all TEXcharacter sequences. Thus the strings
t Q.u and omega represent the Greek letters. and co. Superscripts are created
by typing “;’ subscripts ate created by typing _. To set multiple characters as
superscripts or subscripts, enclose them in ‘braces. For example, type x_{13} to
produce XI3. ‘ ‘; •. ~
. In mathematical text variables are usually set in italic, and functions, like sin,
are set in roman type. To set a character, say, x, in italic using the TEXcommands,
you type { i t x I. To set the t i tl e function using these conventions, you
would type’ . .
»title(‘{it Ae}”{-{it t/tau}}sin({it omega t})’)

Hints CorImproving Plots
The following actions hile not required, can nevertheless improve the appearance
of your plots 1Start scales from zero-whenever possible. This technique prevents a false impression of the magnitudes of any variations shown on the plot.
2. Use sensible tick-mark spacing. For example, if the quantities are months,
choose a spacirlgQf.12 because 1/10 ofa year is not a convenient division.
~ Space tick marks as close as is useful, but no closer. For example, if the data
is given monthly over a range of 24 months, 48 tick marks would be too
dense,’ and also unnecessary Minimize the numr.bzero~ in the data being plotted. For example, use a scale in millions of ddll¥S when appropriate, instead of a scale in dollars with six zeros after every number. 4. Determine the minimum and maximum data values for each axis before plotting the data. Then set the axis limits to cover the entire data range plus an additional amount to allow convenient tick-mark spacing to be selected.

For example, if the data on the x-axis ranges from 1.2 to 9.6, a good choice
for axis limits is 0 to 10. This choice allows you to use a tick spacing of
lor 2.
5. Use a different line type for each curve when several are plotted on a single
plot and they cross each other; for example, use a solid line, a dashed
line, and combinations of lines and symbols. Beware of using colors to
distinguish plots if you are going to make black-and-white printouts and
photocopies.
6. Do not put many curves on one plot, particularly if they will be close to
each other or cross one another at several points.
7. Use the same scale limits and tick spacing on each plot if you need to
compare information on more than one plot.

Related Matlab Homework Assignments

When I learned about Pie plot and other two dimensional plots in MATLAB (MATLAB 2D plot), first time, I was curious to know…

Bar Plots Matlab

Plots matlab
  • What are the other types of 2D plots we can draw in the MATLAB?
  • How to write code to draw 2D plot for all those different plot types?
  • How to make them more colorful?

I started getting more knowledge and doing work on MATLAB R2013a.

I cleared my basic concepts required for plotting different 2D plots. Now I can draw any 2D plots with the various available MATLAB functions.

Here I am sharing my experience with the help of this tutorial. You will find it very interesting plotting different 2D plots and then coloring it.

This tutorial is an extension of our previous tutorial of plotting 2D graphs in MATLAB.

Let’s dive in…

Classifications of Two Dimensional Plots in MATLAB

(MATLAB 2D plot)

Cloud Plots Matlab

MATLAB supports more types of two-dimensional (2D) plots. We are trying to cover plots which are widely used in industry and in different projects.

Here is a list of 10 various MATLAB 2D plots.

  1. Area Plot
  2. Bar Plot
  3. Stem Plot
  4. Stairs Plot
  5. Barh Plot
  6. Pie Plot
  7. Polar Plot
  8. Compass Plot
  9. Scatter Plot
  10. Errorbar Plot

Now, I am describing each 2D plots by using the MATLAB code and its decorating functions in details.

1. Area Plot

In the Area plotting graph, you can use basic functions. It is a very easy draw.

In the MATLAB plotting, there is a function area() to plot Area.

How to draw Area plot in MATLAB?

Syntax:

The syntax for the Area plot…

MATLAB Code:

As an example, we are plotting Area graph for trigonometric function. It is one of the types of functions in MATLAB.

Note:

  • ‘%’ is used to add the comment. The line starts with ‘%’ will get executed.
  • ‘;’ semicolon is used to suppress the entered value.

Output in MATLAB:

After the running code, you will get the Area plot as shown below.

2. Stem Plot

In Stem plot, the discrete sequence data and variables are used. This plot is created by using the stem() function.

How to create the Stem plot in MATLAB?

Syntax:

The syntax for the stem plot is,

Plots Matlab

MATLAB Code:

Here we are creating the stem plot using the MATLAB functions for array of some random discrete numbers.

In this program, I used the color function (red ‘r’) and stem plot function (stem).

Matlab plot label

To decorate your graph, you can learn more about color markers and line specifiers in MATLAB.

Output in MATLAB:

You can see the 2-dimensional stem plot in MATLAB.

3. Bar Plot

You can create different types of bar plot in MATLAB. Here, I am explaining the simple bar plot code with the help of multiple functions.

How to draw Bar plot in MATLAB?

Syntax:

The syntax for the bar plot is,

MATLAB Code:

Let’s write a MATLAB code to plot the Bar for arrays of some random numbers.

Output in MATLAB:

Below is diagram as bar 2-dimensional plot.

4. Barh Plot

Barh plot is short abbreviations of Horizontal bar. Here I am using the Barh function for the horizontal plane.

How to draw a Barh Plot in MATLAB?

Syntax:

The same syntax uses like bar plot,

MATLAB Code:

Output in MATLAB:

Barh plot is showing in the below diagram.

If you look at the above graph, you can see it the exact 90-degree tilt of Bar graph.

5. Errorbar Plot

Errorbar plot is again of the types of bar plot.

How to draw an Errorbar Plot in MATLAB?

Syntax:

The syntax for the Errorbar plot are,

MATLAB Code:

We are adding color function to decorate our plot.

Output in MATLAB:

See the 2-dimensional error plot.

6. Stairs Plot

This is again one of the MATLAB 2D plots that look more like stairs.

How to design the stairs plot in MATLAB?

Syntax:

MATLAB Code:

Here, I am writing the MATLAB code of stairs plot with the black (k) color function.

Output in MATLAB:

Stairs plot is shown in the below diagram. You can design as per your MATLAB code.

It more looks like stairs. Isn’t it?

7. Pie Plot

In mathematics, the pie chart is used to indicate data in percentage (%) form.

In MATLAB, you can draw different kinds of pie plots by using simple code.

How to draw a Pie Plot in MATLAB?

Syntax:

MATLAB Code:

To write the simple code for the pie plot.

We have 7 numbers in the array ‘x’.

When you execute the above code in MATLAB, All the values in array gets converted in the percentage.

Output in MATLAB:

If you look at the code, we have not added any color function. By default, Pie plot is colorful. So it makes plotting Pie graph even easier.

8. Polar Plot

Plotting Polar plot is a little tricky.

When you are plotting the polar plot, theta and radius must be the same size.

How to plot the Polar in MATLAB?

Syntax:

In Polar plot, you can write the following syntax,

Polar plot function has arguments as theta, radius, line specification.

MATLAB Code:

Where ‘r’ considered as the red color.

Output in MATLAB:

The line specification and color are shown in the below diagram. Red dashed depicts the given radius of the circle [2 6 9].

9. Compass Plot

Compass plot is the same as the polar plot. Both need equal quantities of theta and radius.

How to draw a Compass Plot in MATLAB?

Syntax:

The syntax of the compass plot is,

MATLAB Code:

For the designing compass plot, you just need to write only ‘compass’ function.

Output in MATLAB:

10. Scatter Plot

Plotting the scatter plot in MATLAB is simple.

How to draw a Scatter Plot in MATLAB?

Syntax:

For the scatter plot,

MATLAB Code:

Output in MATLAB:

After the running MATLAB code, you will see this…

There are so many 2D plots you can draw in MATLAB. I described briefly the most useful top 10 plots.

In this tutorial, I have covered different types of plots by using examples and different functions [color marker style line spec]. you can read the MATLAB 3D plot with their 5 different classifications.

If you have any query for MATLAB 2D plot, please comment below. I will reply to you as soon as possible.

Stay tuned and See you again…

I have completed master in Electrical Power System. I work and write technical tutorials on the PLC, MATLAB programming, and Electrical on DipsLab.com portal.

Sharing my knowledge on this blog makes me happy. And sometimes I delve in Python programming.