12.3. Histograms and Density Plots
Table of Contents
Understanding Histograms
Histograms show how data values are distributed across different ranges. Instead of plotting each data point separately, a histogram groups values into bins and shows how many values fall into each bin. This is very useful when you have many observations and want to see the overall shape of the data, such as whether it is symmetric, skewed, or has multiple peaks.
In MATLAB, histograms are usually created from a vector of numeric data. Each element of the vector is treated as one observation. Histograms are especially helpful when you want to understand the spread and concentration of values, detect outliers, or compare distributions between different data sets.
Creating Simple Histograms with `histogram`
The basic function to draw a histogram in modern MATLAB is histogram. You call it with a data vector and MATLAB creates a bar-like plot where each bar represents one bin.
A minimal example is:
data = randn(1000,1); % 1000 samples from a normal distribution
histogram(data);
Here, randn produces random values that are roughly bell-shaped around zero. histogram automatically chooses a binning strategy and scales the vertical axis to show counts per bin.
You can store the returned object if you want to modify properties later:
h = histogram(data);
The output h is a histogram object that you can adjust, for example by changing its face color or line style.
Controlling Bin Size and Bin Edges
The appearance and usefulness of a histogram depend strongly on the choice of bins. If bins are too wide, important details are hidden. If bins are too narrow, the plot looks noisy.
MATLAB can choose bins automatically, but you can also control them. The most direct way is to set the number of bins with the NumBins property:
histogram(data,'NumBins',30);
You can also specify the bin edges exactly. This is useful if you know the ranges that matter for your problem. For example, if you want bins from -5 to 5 in steps of 0.5, you can create a vector of edges and pass it to the BinEdges name-value pair:
edges = -5:0.5:5;
histogram(data,'BinEdges',edges);
Once you call histogram, you can modify the bins via the object:
h = histogram(data);
h.NumBins = 50;You can also set the bin width instead of the number of bins:
histogram(data,'BinWidth',0.2);MATLAB adjusts the number of bins to cover the full range of your data with the specified width.
Counts, Normalization, and Histogram Types
By default, histograms show counts, which means the height of each bar equals the number of observations in that bin. Sometimes you want a different interpretation of the vertical axis, such as probabilities or densities, especially when you compare histograms from different sized data sets.
You can use the Normalization property of histogram to change this behavior. Common options include:
Normalizationset to'count'
This is the default. The height is the number of observations in each bin.Normalizationset to'probability'
The height is the fraction of the total number of observations in each bin. All bar heights sum to 1.Normalizationset to'pdf'
The histogram is scaled so that the total area equals 1. The heights approximate a probability density function (PDF). This is often used when overlaying theoretical probability densities or other smooth curves.Normalizationset to'countdensity'
This is similar to'pdf'but in terms of counts per unit on the x-axis. The area under the bars gives the total number of observations.
Here is an example with probabilities:
histogram(data,'Normalization','probability');And an example with a density:
histogram(data,'Normalization','pdf');
When using 'pdf', the vertical axis can be larger than 1 if bins are narrow. The key property is that the total area under all bars equals 1.
Overlaying Histograms for Comparison
To compare distributions from different samples, you often want to display more than one histogram in the same figure. There are two common arrangements: stacked histograms and overlaid histograms.
To overlay, you can call hold on and then draw multiple histograms. To avoid one histogram completely hiding the other, you can adjust the transparency through the FaceAlpha property and possibly use the same bin edges for both data sets.
For example:
data1 = randn(1000,1);
data2 = 1 + randn(800,1); % shifted data
edges = -4:0.25:6;
h1 = histogram(data1,'BinEdges',edges,...
'Normalization','probability',...
'FaceColor',[0 0.4470 0.7410],...
'FaceAlpha',0.5);
hold on;
h2 = histogram(data2,'BinEdges',edges,...
'Normalization','probability',...
'FaceColor',[0.8500 0.3250 0.0980],...
'FaceAlpha',0.5);
hold off;Using consistent bin edges is important for a meaningful comparison. If each histogram chooses its own bins, the shapes are harder to compare. Transparency lets you see both data sets where they overlap.
You can also use separate axes or subplots, which is covered in other chapters, when overlapping becomes confusing.
Histogram Objects and Customization
The histogram function returns a histogram object. This object has properties you can inspect and modify to adjust the visual appearance and behavior of the plot.
After creating a histogram
h = histogram(data);you can query or change properties such as:
h.FaceColor = 'k'; % black bars
h.EdgeColor = 'w'; % white edges
h.LineWidth = 1.5; % thicker borders
h.FaceAlpha = 0.3; % semi transparent barsThe object also stores computed values, for example the bin counts and bin edges:
counts = h.Values;
edges = h.BinEdges;These values can be useful if you want to perform additional calculations based on the histogram, such as computing cumulative counts or manually drawing extra elements on the plot.
Understanding Density Plots
While histograms use rectangles to approximate the distribution of data, density plots represent the same idea with a smooth curve. The main concept is a probability density function (PDF). A PDF describes how likely it is to observe values in a small interval around each point on the horizontal axis.
A smooth density plot can make it easier to see the overall shape of the distribution, such as multiple peaks, without being too sensitive to the choice of bin edges. Density plots are often constructed through kernel density estimation, which spreads each data point with a smooth kernel function and then sums the contributions.
In MATLAB, densities are often viewed in connection with 'pdf' normalized histograms, or using external functions that perform kernel density estimation.
Approximating Density with Normalized Histograms
If you normalize a histogram with Normalization set to 'pdf', the bar heights approximate an underlying density. As the number of data points increases and the bins become smaller, the histogram with 'pdf' normalization tends to resemble the true density more closely.
For example:
data = randn(5000,1);
histogram(data,'Normalization','pdf');To emphasize the density view, you can hide the edges and use a filled style:
h = histogram(data,'Normalization','pdf');
h.EdgeColor = 'none';
If you want an even smoother appearance, you can combine a 'pdf' normalized histogram with a continuous curve, usually from a density estimate or a known theoretical distribution.
Kernel Density Estimation with `ksdensity`
MATLAB provides the function ksdensity for kernel density estimation. This function takes your data and returns points along the x-axis together with estimated density values. You can then plot these as a smooth curve.
A basic usage pattern is:
data = randn(1000,1);
[x,f] = ksdensity(data);
plot(x,f,'LineWidth',2);
Here, x is a vector of evaluation points sorted in increasing order. f is the estimated density at these points. The curve integrates to 1, which means it represents a probability density.
To compare the density estimate with a histogram, you can overlay them:
histogram(data,'Normalization','pdf');
hold on;
[x,f] = ksdensity(data);
plot(x,f,'r','LineWidth',2);
hold off;This combination often gives a nice visual summary, where the histogram shows the raw bin structure while the curve highlights the overall trend.
The function ksdensity chooses sensible defaults for the number of evaluation points and the kernel bandwidth, but you can adjust them using name-value pairs. Basic use for beginners usually works well with defaults.
Choosing Between Histograms and Density Plots
Both histograms and density plots describe how data are distributed, but they emphasize different aspects.
Histograms directly reflect counts in bins. They show discrete groupings that depend on bin edges. Histograms are intuitive and closely tied to how many observations fall in each interval. They are very common in exploratory analysis and are easy to interpret for beginners.
Density plots with a function like ksdensity emphasize a smooth view of the distribution. They can reveal features like multiple modes more clearly, especially when there is a lot of data. However, they depend on choices like bandwidth, and they can hide some discrete aspects of the data.
In practice, many users begin with a histogram, then add a smooth density curve if more detail is needed. For example, you might start with:
histogram(data);and then, if you suspect a particular shape, refine it to:
histogram(data,'Normalization','pdf');
hold on;
[x,f] = ksdensity(data);
plot(x,f,'r','LineWidth',2);
hold off;Visual Interpretation of Distribution Shape
When you look at a histogram or density plot, you are mainly interested in the shape of the distribution.
If the bars cluster around the center and fall off symmetrically, the distribution resembles a normal distribution. If there is a long tail on one side, the distribution is skewed. Heavy tails show more extreme values than a normal distribution would suggest, while several peaks indicate that there might be subgroups or mixtures of populations in the data.
You can change bin settings or bandwidths to check whether apparent features are real or just artifacts of the plotting choices. A pattern that persists as you adjust these settings is likely to be meaningful.
Density plots are especially helpful when distributions overlap. If you overlay two smooth curves, their differences in location and spread become easier to see than if you only look at overlapping bars.
Working with Logarithmic Scales for Histograms
Sometimes the data span several orders of magnitude. In such cases, it can be helpful to display the histogram on a logarithmic scale, usually along the horizontal axis.
You can use axis scaling commands on a histogram just as you would on other plots. For example:
data = lognrnd(0,1,1000,1); % lognormal data
histogram(data);
set(gca,'XScale','log');This keeps the histogram bars but changes the scale for reading the values. Be aware that the interpretation of bin widths changes, since equal spacing on a log axis corresponds to multiplicative changes in the original scale.
Using log scales can reveal patterns that are invisible on a linear scale, such as multiplicative relationships or power law behaviors.
Important points to remember:
- Use
histogramfor basic histograms, and control binning withNumBins,BinWidth, orBinEdges. - Change
Normalizationto'probability'or'pdf'when comparing samples or approximating densities. - Use consistent bin edges and transparency when overlaying multiple histograms.
- Use
ksdensityto create smooth density curves and overlay them on'pdf'normalized histograms. - Adjust axes and visual properties through the histogram object to clarify the shape of distributions.
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!