Kahibaro
Discord Login Register

Bar, Scatter, and Stem Plots

Overview

In this chapter you learn how to create and customize three very common plot types in MATLAB: bar plots, scatter plots, and stem plots. All three are built on top of the same plotting system, but each is suited to slightly different types of data and questions. You will see how to create them from numeric vectors and matrices, how to control some basic appearance options, and how to interpret the axes and plotted values.

Bar plots

A bar plot represents numeric values as the heights or lengths of rectangular bars. Bar plots are useful for visualizing categories, counts, or any situation where the actual numeric values and their relative sizes matter more than the exact shapes of curves.

The basic command for vertical bar plots is bar. If y is a numeric vector, then:

matlab
y = [3 5 2 7];
bar(y);

creates a figure where the x axis shows the element indices 1, 2, 3, 4 and the y axis shows the values 3, 5, 2, and 7 as bar heights.

If you provide both x and y, MATLAB uses x for bar positions:

matlab
x = [10 20 30 40];
y = [3 5 2 7];
bar(x, y);

In this case the x axis shows 10, 20, 30, and 40 at the center of each bar. This is useful when your data are sampled at irregular x values.

Grouped and stacked bar plots

When bar receives a matrix Y instead of a vector, each column of Y is treated as a separate series. By default MATLAB draws these as grouped bars at each x position. For example:

matlab
Y = [3 5 4;   % row 1
     2 6 1;   % row 2
     4 3 5];  % row 3
bar(Y);

Each row corresponds to one x position. At each x position MATLAB will draw three bars next to each other, one for each column.

You can change the style to stacked bars by adding a mode argument:

matlab
bar(Y, 'stacked');

Now at each x position the bars for each row are stacked on top of each other, so the total height equals the sum of the row elements. Stacked bars are handy when you care about both the total and the contributions of individual components.

Bar width, orientation, and basic appearance

By default, bars are vertical. To create horizontal bars, use barh:

matlab
y = [3 5 2 7];
barh(y);

Horizontal bar plots are especially useful when category labels are long or when you want to emphasize rank on the vertical axis.

You can control the width of bars with the 'BarWidth' property as a name-value pair:

matlab
y = [3 5 2 7];
bar(y, 'BarWidth', 0.5);

A BarWidth of 1 uses the full available gap, and smaller values make the bars thinner with more space between groups.

You can also change colors. If you call bar with an output argument, you get a bar object handle that you can modify:

matlab
y = [3 5 2 7];
b = bar(y);
b.FaceColor = 'flat';          % enable per-bar colors
b.CData    = [1 0 0;           % red
              0 1 0;           % green
              0 0 1;           % blue
              0.5 0.5 0.5];    % gray

Here CData contains one RGB triplet per bar when FaceColor is 'flat'. For uniform color on all bars you can simply set b.FaceColor = [0.2 0.6 0.8]; or use a named color such as 'r' for red.

Simple example with category labels

Often bar plots represent categories like names or groups. In that case it is useful to control the x tick labels while leaving the x values as indices:

matlab
values = [12 18 9 15];
labels = {'A', 'B', 'C', 'D'};
bar(values);
xticks(1:numel(values));
xticklabels(labels);

The actual x values remain 1, 2, 3, and 4, but the tick labels show A, B, C, and D. You can combine this with titles, axis labels, and legends to create clear summary plots of category data.

Scatter plots

Scatter plots show individual data points as markers in the plane. They are most useful when you want to study the relationship between two numeric variables, or when the sample is irregular so that connecting points with lines might be misleading.

The basic command is scatter. If x and y are vectors of the same length, then:

matlab
x = 1:10;
y = x.^2;
scatter(x, y);

plots each pair (x(i), y(i)) as a marker. Unlike plot, scatter does not connect points with lines by default. You can think of each point as representing a single observation.

Marker size and color

The simplest form scatter(x, y) uses default marker size and color. You can control marker size with a third argument sz, and marker color with a fourth argument c. For example:

matlab
x = randn(1, 50);
y = randn(1, 50);
sz = 50;                 % all markers radius-like size
scatter(x, y, sz, 'filled');

The 'filled' option fills the marker interior with color.

If you pass a vector for sz, each point can have a different size. Similarly, if you pass a vector or matrix for c, each point can have a different color, often mapped through a colormap:

matlab
x = randn(1, 100);
y = randn(1, 100);
sz = 20 * ones(1, 100);
c  = y;                 % color determined by y values
scatter(x, y, sz, c, 'filled');
colorbar;

In this code c is a vector, so MATLAB uses the current colormap to convert numeric values into colors. colorbar shows the mapping between numeric values and colors.

Marker style and basic customization

You choose a marker style through the 'Marker' property or in a format string. With scatter it is common to set it via name-value pairs:

matlab
x = 1:10;
y = x + randn(1, 10);
s = scatter(x, y, 'filled');
s.Marker = 'o';          % circle
s.MarkerEdgeColor = 'k';
s.MarkerFaceColor = 'g';

Some common marker symbols are 'o' for circles, 's' for squares, 'd' for diamonds, 'x' for x-marks, and '+' for plus signs. You can mix scatter plots with lines created by plot when you want to emphasize both individual observations and a general trend:

matlab
x = linspace(0, 2*pi, 30);
y = sin(x) + 0.1*randn(size(x));
scatter(x, y, 40, 'b', 'filled');
hold on;
plot(x, sin(x), 'r', 'LineWidth', 2);
hold off;

Here the scatter plot shows noisy observations while the red line shows the underlying smooth function.

Scatter with transparency

Transparency helps when points overlap heavily, because it lets dense regions appear darker. This is very useful when you have many thousands of points.

For modern versions of MATLAB you can set the 'MarkerFaceAlpha' property of the scatter object:

matlab
x = randn(1, 2000);
y = randn(1, 2000);
s = scatter(x, y, 12, 'b', 'filled');
s.MarkerFaceAlpha = 0.2;   % 0 means fully transparent, 1 means opaque

With a low face alpha value, regions where many points overlap become visibly darker, which gives you a sense of density without resorting to a separate histogram or density plot.

Stem plots

A stem plot represents data values as lines or “stems” rising from a baseline at zero up to a marker that indicates the actual value at each x location. Stem plots sit somewhere between bar and scatter plots. They are often used for discrete sequences in signal processing or to show impulse-like data where the locations and heights matter more than the space between them.

Use the stem command to create stem plots. With a single input vector:

matlab
y = [0.2 1.0 0.5 1.5 0.7];
stem(y);

MATLAB plots stems at integer x positions 1, 2, 3, 4, and 5, each ending at the corresponding y value.

To specify x positions explicitly, use:

matlab
n = -2:2;
y = [0.2 1.0 0.5 1.5 0.7];
stem(n, y);

In this example the stems originate at x values −2 to 2. Using explicit x values is especially common for sampled signals, where you might label samples with an index n.

Multiple sequences in one stem plot

If you provide a matrix Y to stem, MATLAB plots one stem series for each column, similar to plot:

matlab
n = 0:5;
y1 = sin(n);
y2 = cos(n);
stem(n, [y1.' y2.']);   % columns for two sequences
legend('sin', 'cos');

Each sequence is drawn with its own color and marker style. Using hold on you can also manually combine stems from separate calls to have more control over styles.

Appearance: line, marker, and baseline

The stem function returns stem series objects that you can customize. A basic example:

matlab
n = 0:10;
y = exp(-0.3*n);
h = stem(n, y);

The variable h is a Stem object with child objects that control the line, markers, and baseline. You can adjust some properties directly:

matlab
h.Marker = 'o';
h.MarkerFaceColor = 'r';
h.LineStyle = '-';
h.LineWidth = 1.5;

The baseline is the horizontal line from which stems originate, usually at zero. You can show or hide it with:

matlab
h.BaseValue = 0;           % y position of the baseline
h.ShowBaseLine = 'off';    % hide the baseline

Hiding the baseline can make the figure cleaner when the zero line is not very important, or when you want to emphasize just the stems and markers.

Comparison with bar and scatter plots

Although bar, scatter, and stem plots all accept similar vector inputs, the visual effect is different and fits different tasks.

Use a bar plot when you want to emphasize the magnitude of values over categories or time intervals, especially when the values represent totals, counts, or contributions. The space between bars suggests separate, often categorical, quantities.

Use a scatter plot when you want to show individual data points of two variables together, in order to see patterns, clusters, or relationships. Scatter plots treat each point as an independent observation.

Use a stem plot when your data are discrete samples at specific x positions, and you want to highlight both the locations and the values without filling the space between them. This is common in sampled signals and impulse responses.

You can combine different plot types in one figure when it helps your explanation. For example, you might plot a continuous theoretical function with plot, then overlay discrete sample values with stem to show how a continuous signal is sampled.

Important points to remember:

  1. Use bar for categorical or grouped numeric values, barh for horizontal bars, and matrices with bar for grouped or stacked bars.
  2. Use scatter to visualize relationships between two numeric variables, and control marker size and color using size and color arguments or properties like MarkerFaceColor and MarkerFaceAlpha.
  3. Use stem for discrete sequences where values occur at specific x positions, and customize stems, markers, and the baseline through the returned stem object.

Views: 4

Comments

Please login to add a comment.

Don't have an account? Register now!