Create Graph with Two y-Axes

This example shows how to create a graph with two y-axes, label the axes, and display the grid lines.

Create and Plot Data

Create the data.

A = 1000;
a = 0.005;
b = 0.005;
t = 0:900;
z1 = A*exp(-a*t);
z2 = sin(b*t);

Use plotyy to create a graph with two y-axes. Plot z1 versus t using semilogarithmic scaling. Plot z2 versus t using linear scaling. Return the two axes in array ax, and return the two lines as p1 and p2.

[ax,p1,p2] = plotyy(t,z1,t,z2,'semilogy','plot');

The left y-axis corresponds to the first set of data plotted, which is the semilogarithmic plot for z1. The first axes, ax(1), and the line, p1, correspond to the first set of data.

The right y-axis corresponds to the second set of data plotted, which is the line plot for z2. The second axes, ax(2), and the line, p2, correspond to the second set of data.

Label the Axes

Label the left y-axis by passing the first axes to the ylabel function. Then, label the right y-axis by passing the second axes to the ylabel function. Label the x-axis using either axes.

ylabel(ax(1),'Semilog Plot') % label left y-axis
ylabel(ax(2),'Linear Plot') % label right y-axis
xlabel(ax(2),'Time') % label x-axis

Modify Line Appearance

Change the appearance of the lines. Starting in R2014b, you can use dot notation to set properties. If you are using an earlier release, use the set function instead.

p1.LineStyle = '--';
p1.LineWidth = 2;
p2.LineWidth = 2;

Display Grid Lines

Display the log grid associated with the left y-axis by passing the first axes to the grid function.

grid(ax(1),'on')

To display the linear grid associated with the right y-axis instead, use grid(ax(2),'on').

See Also

| |

Related Examples

Was this topic helpful?