12.2. Bar, Scatter, and Stem Plots
Table of Contents
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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:
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 opaqueWith 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:
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:
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:
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:
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:
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:
h.BaseValue = 0; % y position of the baseline
h.ShowBaseLine = 'off'; % hide the baselineHiding 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:
- Use
barfor categorical or grouped numeric values,barhfor horizontal bars, and matrices withbarfor grouped or stacked bars. - Use
scatterto visualize relationships between two numeric variables, and control marker size and color using size and color arguments or properties likeMarkerFaceColorandMarkerFaceAlpha. - Use
stemfor discrete sequences where values occur at specific x positions, and customize stems, markers, and the baseline through the returned stem object.
Views: 0
Where to Move
Move chapter:
- ☰ 1. Getting Started with MATLAB
- ☰ 1.1. What Is MATLAB and What Is It Used For
- ☰ 1.2. Installing MATLAB and Setting Up the Environment
- ☰ 1.3. Understanding the MATLAB Desktop Interface
- ☰ 1.4. Command Window, Workspace, and Current Folder
- ☰ 1.5. Basic Workflow and Running Simple Commands
- ☰ 1.6. Getting Help and Documentation
-
- ☰ 2. MATLAB Language Basics
- ☰ 2.1. MATLAB Syntax and Expressions
- ☰ 2.2. Variables and Assignment
- ☰ 2.3. Data Types and Type Conversion
- ☰ 2.4. Vectors and Matrices Fundamentals
- ☰ 2.5. Creating and Indexing Arrays
- ☰ 2.6. Basic Arithmetic and Elementwise Operations
- ☰ 2.7. Using Built-In Constants and Functions
-
- ☰ 3. Working with Variables and the Workspace
- ☰ 3.1. Creating, Viewing, and Editing Variables
- ☰ 3.2. Workspace Browser and Variable Inspector
- ☰ 3.3. Saving and Loading Data Files
- ☰ 3.4. MAT-Files and Importing External Data
- ☰ 3.5. Clearing Variables and Managing the Workspace
-
- ☰ 4. Vectors, Matrices, and Arrays
- ☰ 4.1. Row and Column Vectors
- ☰ 4.2. Matrix Creation and Concatenation
- ☰ 4.3. Indexing, Slicing, and Logical Indexing
- ☰ 4.4. Matrix Operations vs Elementwise Operations
- ☰ 4.5. Reshaping and Rearranging Arrays
- ☰ 4.6. Special Matrices and Functions
-
- ☰ 5. Basic Programming Constructs
- ☰ 5.1. Scripts vs Functions
- ☰ 5.2. Control Flow with if, elseif, else
- ☰ 5.3. Loops with for and while
- ☰ 5.4. break, continue, and return
- ☰ 5.5. Logical Expressions and Relational Operators
- ☰ 5.6. Best Practices for Clear and Readable Code
-
- ☰ 6. Functions in MATLAB
- ☰ 6.1. Creating Simple Functions
- ☰ 6.2. Function Inputs and Outputs
- ☰ 6.3. Function Files and the Path
- ☰ 6.4. Local vs Global Variables
- ☰ 6.5. Anonymous Functions
- ☰ 6.6. Organizing Code into Multiple Functions
-
- ☰ 7. Working with Numbers and Math
- ☰ 7.1. Scalars and Vectorized Computations
- ☰ 7.2. Basic Mathematical Functions
- ☰ 7.3. Trigonometric and Exponential Functions
- ☰ 7.4. Complex Numbers in MATLAB
- ☰ 7.5. Rounding, Modulo, and Special Values
- ☰ 7.6. Numerical Precision and Floating Point Considerations
-
- ☰ 8. Strings, Characters, and Categorical Data
- ☰ 8.1. Character Arrays and String Arrays
- ☰ 8.2. Creating and Manipulating Strings
- ☰ 8.3. Converting Between Data Types and Strings
- ☰ 8.4. Comparing and Searching Strings
- ☰ 8.5. Categorical Arrays Basics
-
- ☰ 9. Tables, Structures, and Cell Arrays
- ☰ 9.1. Introduction to Tables
- ☰ 9.2. Creating Tables and Accessing Data
- ☰ 9.3. Modifying and Joining Tables
- ☰ 9.4. Structures and Nested Structures
- ☰ 9.5. Cell Arrays and Cell Indexing
- ☰ 9.6. Choosing the Right Container Type
-
- ☰ 10. Importing and Exporting Data
- ☰ 10.1. Reading Text and CSV Files
- ☰ 10.2. Importing Excel Spreadsheets
- ☰ 10.3. Importing Data with the Import Tool
- ☰ 10.4. Exporting Data to Files
- ☰ 10.5. Working with Image and Audio Files
- ☰ 10.6. Basic File Management from MATLAB
-
- ☰ 11. Plotting and Visualization
- ☰ 11.1. Introduction to 2D Plotting
- ☰ 11.2. Customizing Plots and Axes
- ☰ 11.3. Multiple Plots in One Figure
- ☰ 11.4. Labels, Titles, Legends, and Annotations
- ☰ 11.5. Plotting with Different Line and Marker Styles
- ☰ 11.6. Saving and Exporting Figures
-
- ☰ 12. Advanced Plotting for Beginners
- ☰ 12.1. Subplots and Tiled Layouts
- ☰ 12.2. Bar, Scatter, and Stem Plots
- ☰ 12.3. Histograms and Density Plots
- ☰ 12.4. 3D Plots and Surface Plots
- ☰ 12.5. Using plottools and Interactive Editing
- ☰ 12.6. Basics of Handle Graphics
-
- ☰ 13. Working with Scripts and Live Scripts
- ☰ 13.1. Creating and Running Script Files
- ☰ 13.2. Sectioning Code and Running Sections
- ☰ 13.3. Live Scripts and Rich Text
- ☰ 13.4. Adding Equations, Images, and Outputs
- ☰ 13.5. Sharing and Exporting Live Scripts
-
- ☰ 14. Debugging and Code Quality
- ☰ 14.1. Finding and Fixing Syntax Errors
- ☰ 14.2. Setting Breakpoints and Stepping Through Code
- ☰ 14.3. Inspecting Variable Values During Execution
- ☰ 14.4. Using the Editor Debugging Tools
- ☰ 14.5. Using Code Analyzer and Warnings
- ☰ 14.6. Writing Clean and Maintainable MATLAB Code
-
- ☰ 15. Basic Linear Algebra with MATLAB
- ☰ 15.1. Vectors and Norms
- ☰ 15.2. Matrix Addition and Multiplication
- ☰ 15.3. Solving Linear Systems with Backslash
- ☰ 15.4. Inverses, Determinants, and Rank
- ☰ 15.5. Eigenvalues and Eigenvectors
- ☰ 15.6. Using Linear Algebra Functions Safely
-
- ☰ 16. Data Analysis and Statistics Fundamentals
- ☰ 16.1. Descriptive Statistics and Summary Measures
- ☰ 16.2. Sorting, Filtering, and Grouping Data
- ☰ 16.3. Basic Correlation and Regression
- ☰ 16.4. Simple Data Cleaning Techniques
- ☰ 16.5. Basic Time Series Handling
-
- ☰ 17. Working with Time and Dates
- ☰ 17.1. Representing Dates and Times
- ☰ 17.2. Creating and Formatting datetime Arrays
- ☰ 17.3. Date Calculations and Differences
- ☰ 17.4. Plotting Data over Time
-
- ☰ 18. Introduction to Signal and Image Handling
- ☰ 18.1. Basic Signal Representation in MATLAB
- ☰ 18.2. Simple Filtering and Transformations
- ☰ 18.3. Reading, Displaying, and Writing Images
- ☰ 18.4. Basic Image Transformations
-
- ☰ 19. Automation and Scripting Tasks
- ☰ 19.1. Batch Processing of Files
- ☰ 19.2. Writing Reusable Utility Scripts
- ☰ 19.3. Using Relative Paths and the MATLAB Path
- ☰ 19.4. Simple User Interaction with input and disp
-
- ☰ 20. Introduction to Toolboxes
- ☰ 20.1. What Are Toolboxes and How to Use Them
- ☰ 20.2. Exploring Installed Toolboxes
- ☰ 20.3. Finding Functions in Toolboxes
- ☰ 20.4. Add-Ons and MATLAB File Exchange
-
- ☰ 21. Best Practices and Next Steps
- ☰ 21.1. Organizing Projects and Folders
- ☰ 21.2. Version Control Basics with MATLAB
- ☰ 21.3. Performance Tips for Beginners
- ☰ 21.4. Learning Resources and Documentation Path
- ☰ 21.5. Suggested Practice Projects for Beginners
-
Comments
Please login to add a comment.
Don't have an account? Register now!