Drawing Multiple Functions on the Same Graph



Prev TutorialNext Tutorial

You can draw multiple graphs on the same plot. The following example demonstrates the concept −

Example

Create a script file and type the following code −
x = [0 : 0.01: 10];
y = sin(x);
g = cos(x);
plot(x, y, x, g, '.-'), legend('Sin(x)', 'Cos(x)')
MATLAB generates the following graph −
Multiple Functions on the Same Graph

Setting Colors on Graph

MATLAB provides eight basic color options for drawing graphs. The following table shows the colors and their codes −
CodeColor
wWhite
kBlack
bBlue
rRed
cCyan
gGreen
mMagenta
yYellow

Example

Let us draw the graph of two polynomials
  • f(x) = 3x4 + 2x3+ 7x2 + 2x + 9 and
  • g(x) = 5x3 + 9x + 2
Create a script file and type the following code −
x = [-10 : 0.01: 10];
y = 3*x.^4 + 2 * x.^3 + 7 * x.^2 + 2 * x + 9;
g = 5 * x.^3 + 9 * x + 2;
plot(x, y, 'r', x, g, 'g')
When you run the file, MATLAB generates the following graph −
Colors on Graph

Setting Axis Scales

The axis command allows you to set the axis scales. You can provide minimum and maximum values for x and y axes using the axis command in the following way:
axis ( [xmin xmax ymin ymax] )
The following example shows this −

Example

Create a script file and type the following code −
x = [0 : 0.01: 10];
y = exp(-x).* sin(2*x + 3);
plot(x, y), axis([0 10 -1 1])
When you run the file, MATLAB generates the following graph −
Setting Axis Scales

Generating Sub-Plots

When you create an array of plots in the same figure, each of these plots is called a subplot. The subplot command is used for creating subplots.
Syntax for the command is −
subplot(m, n, p)
where, m and n are the number of rows and columns of the plot array and pspecifies where to put a particular plot.
Each plot created with the subplot command can have its own characteristics. Following example demonstrates the concept −

Example

Let us generate two plots −
y = e−1.5xsin(10x)
y = e−2xsin(10x)
Create a script file and type the following code −
x = [0:0.01:5];
y = exp(-1.5*x).*sin(10*x);
subplot(1,2,1)
plot(x,y), xlabel('x'),ylabel('exp(–1.5x)*sin(10x)'),axis([0 5 -1 1])
y = exp(-2*x).*sin(10*x);
subplot(1,2,2)
plot(x,y),xlabel('x'),ylabel('exp(–2x)*sin(10x)'),axis([0 5 -1 1])
When you run the file, MATLAB generates the following graph −
Generating Sub-Plots