Documentation Center

  • Trial Software
  • Product Updates

Combine Stem Plot and Line Plot

This example shows how to create a graph with a stem plot and a line plot.

Define x as a vector with 60 linearly spaced elements. Define a and b as sine and cosine values.

x = linspace(0,2*pi,60);
a = sin(x);
b = cos(x);

Create a stem plot of the linear combination of a and b. Return the handles to the stemseries object created by the stem function.

hStem = stem(x,a+b);

To retain the stem plot so that the plot command does not replace it, set the hold state to on. Overlay the stem plot with line plots of a and b. Specify a different color for each line and use a dashed line style. Return the handles to the line objects created.

hold on
hLine = plot(x,a,'--r',x,b,'--g');
hold off

To add a legend to the graph, use the legend function. Pass the stemseries handle and line object handles to legend.

h = [hStem; hLine];
legend(h,'a+b','a = sin(x)','b = cos(x)')

Label the axis and add a title to the graph.

xlabel('Time in \musecs')
title('Linear Combination of Two Functions')

Was this topic helpful?