A histogram is a graphical representation of the distribution of numerical data in which observations are grouped into intervals, called bins, and represented by rectangles. The horizontal extent of each rectangle identifies an interval of values; its height represents a count, a relative frequency, or a density. When bin widths differ, rectangle areas rather than heights must represent the frequencies if the display is to preserve its distributional meaning.
Histograms are fundamental tools in statistics, data science, and scientific measurement because they reveal features that a single numerical summary cannot: asymmetry, gaps, concentrations, long tails, and possible multiple modes. They also serve as elementary estimators of a probability distribution and as computational representations of large datasets. Their apparent simplicity conceals important choices about interval width, interval alignment, normalization, and measurement scale. These choices determine both what the display reveals and what it can obscure.
Mathematical definition and normalization
Let be numerical observations, and let an increasing sequence of bin edges be
A usual convention defines bin as , except that the final bin may include its right endpoint. The count in bin is
where is an indicator function. If the bins cover all observations without overlap, then . The endpoint convention matters for observations that fall exactly on bin boundaries, particularly when measurements have been rounded.
Several normalizations are common. A count histogram uses height , while a relative-frequency histogram uses height . With equal-width bins, both produce the same shape up to a constant vertical scale. Counts answer how many observations occupy an interval; relative frequencies answer what fraction of the observations occupy it. Neither convention automatically makes the total rectangle area equal to one.
A density histogram instead has height
where . Its rectangle areas sum to one:
It therefore defines a piecewise-constant probability density function. The height has units inverse to those of the horizontal variable. For measurements in seconds, density is measured in inverse seconds; only an area gives a dimensionless probability. A density height can exceed one without violating any probability rule.
For example, suppose 100 observations produce 20 values in and 30 values in . Their relative frequencies are and , but their density heights are and . The second interval contains more observations yet has a lower density because it is twice as wide. Drawing unequal-width rectangles with heights 20 and 30 would give areas 20 and 60, exaggerating the second interval’s share. This distinction is essential whenever bins have unequal widths.
A histogram may also show frequency density, with height . In that convention, rectangle area equals count and total area equals , rather than one. Clear vertical-axis labeling distinguishes these conventions.
Constructing bins and preserving measurement meaning
Constructing a histogram begins with specifying the variable, its measurement scale, and the observations eligible for inclusion. Numerical codes do not necessarily describe numerical quantities: postal codes and category identifiers, for example, have no meaningful intervening values. Grouping such codes into numerical intervals would create a visual distribution without a corresponding quantitative interpretation. Histograms are appropriate when intervals and their widths have a substantive meaning.
For continuous measurements, equal-width bins are the most common starting point. Given a width and an origin , bins can be written as
for successive integers . Both and matter. Moving the origin while retaining the width changes which nearby observations are grouped together. A cluster lying across an edge may appear split; after a shift of half a bin width, it may appear as a single prominent rectangle. This alignment effect is particularly strong in small samples or data with tightly concentrated groups.
Discrete numerical data require additional care. For integer-valued observations such as counts of defects, bins centered on integers with edges at half-integers can show each possible count without an arbitrary boundary passing through it. If every possible value is represented separately, the display closely resembles a plot of a probability mass function. Combining integers into wider intervals may still be useful when the range is large, but it discards distinctions among the values grouped together.
The displayed range should be distinguished from the population of observations used for normalization. If observations outside a selected range are excluded and the remaining data are renormalized to total probability one, the histogram represents the distribution conditional on falling inside that range. If the original denominator is retained, its displayed area may be less than one. Cropping a plot and discarding data are therefore different operations, even when their visible rectangles look similar.
Measurements near boundaries also require explicit treatment. Durations cannot be negative, and proportions lie between zero and one. Bins extending outside a variable’s possible range can waste space or complicate density interpretation. Open-ended classes, such as “100 or more,” have no finite width and consequently cannot be assigned an ordinary finite-width density rectangle without an additional convention.
Rounding and digit preference can create artificial spikes. Ages recorded in completed years, laboratory readings rounded to a fixed resolution, and reported quantities favoring multiples of five may all show patterns originating in recording practices. Bin edges chosen in relation to the measurement resolution help distinguish such effects from genuine features of the underlying quantity.
Reading shape, concentration, and unusual observations
A histogram presents a distribution through its shape, but each visible feature depends partly on the chosen grouping. The main descriptive questions concern where observations concentrate, how widely they spread, whether the two sides have similar shapes, and whether there are distinct peaks or gaps. These are aspects of exploratory data analysis, not automatic conclusions about the mechanism that generated the data.
A roughly symmetric histogram has comparable structure on either side of a central region. A right-skewed distribution has a longer or more extended upper tail, while a left-skewed distribution has a longer lower tail. The direction of skewness refers to the tail rather than the location of the highest bar. Positive quantities such as transaction sizes or waiting times often have many small observations and relatively few large ones, although the exact shape depends on the process and sampling scheme.
Peaks suggest modes, or regions of locally high concentration. A bimodal histogram may arise from a mixture of subpopulations, such as measurements from two production lines with different operating settings. It may also result from rounding, periodic structure, or a particular choice of bins. A Gaussian mixture model can represent some such distributions, but two visible peaks do not by themselves establish that exactly two underlying groups exist. Conversely, overlapping groups may produce only one visible peak.
The histogram conveys spread through the extent and allocation of its occupied intervals. It does not ordinarily determine the exact sample mean, median, or standard deviation, because the positions of observations within each interval have been discarded. Two datasets can have identical bin counts but different means and variances. Approximate numerical summaries can be calculated by treating each bin’s observations as if they occurred at its midpoint, but those approximations depend on bin width and within-bin structure.
Isolated bars or thinly populated tails can indicate unusual observations, yet their interpretation requires context. A distant value may be a recording error, a legitimate rare event, or evidence that a proposed distribution is inadequate. An empty bin does not establish that the corresponding population probability is zero, especially with a small sample size. Likewise, a jagged histogram need not imply a highly irregular underlying density.
A histogram also discards observation order. Two sequences containing the same values in different orders have identical histograms even if one exhibits a trend and the other does not. In a time series, shifts, cycles, or alternating regimes can disappear when all observations are pooled. Histograms describe the distribution of values, not their temporal arrangement, spatial organization, or causal relationships.
Choosing bin width and bin number
Bin width controls a central compromise: narrow bins preserve local detail but make sampling fluctuations more visible, while wide bins suppress fluctuations but can merge important structure. This is an instance of the bias–variance tradeoff. There is no single width that is best for every dataset, purpose, or underlying distribution. Published selection rules provide reference values rather than universally correct answers.
Herbert Sturges proposed a rule in 1926 that is commonly written
It yields a bin number growing logarithmically with sample size. For , it gives 11 bins. Sturges’s rule is simple and remains widely implemented, but its slow growth can produce excessively coarse histograms for large samples or distributions with substantial structure. Its historical motivation uses a binomial frequency pattern approximating a bell-shaped distribution.
David W. Scott’s 1979 normal-reference rule selects the width
where is the sample standard deviation. The constant is obtained from an asymptotic calculation under a normal distribution reference model. The dependence on gives the rule the appropriate measurement units, while makes bins narrower as more observations become available. Extreme observations can inflate , potentially leading to a width that is too large for the main body of a heavy-tailed sample.
The rule associated with David Freedman and Persi Diaconis, published in 1981, uses
where the interquartile range is the difference between the upper and lower quartiles. This spread measure is less sensitive to extreme tails than the standard deviation. For and an interquartile range of 12 units, the width is units. Different software conventions for sample quantiles can produce slightly different numerical widths.
These rules can fail in degenerate or unusual cases. If most observations are identical, the interquartile range may be zero even when a few values differ. A constant dataset has no empirical spread from which either scale-based rule can derive a positive width. A single extreme observation may make the overall range very large, creating many empty bins when the width is based on the central distribution.
Data-driven methods can instead select bins using penalized likelihood, cross-validation, or Bayesian inference. Such methods optimize a stated criterion and may choose unequal widths or adapt to local structure. They still embody assumptions about what constitutes a useful approximation. A distributional feature that appears only under one narrowly chosen width or alignment is weaker evidence than one visible across several reasonable choices.
Histograms as statistical estimators
Beyond their graphical role, histograms are elementary tools for density estimation. Suppose are independent observations from a distribution with density . For a fixed bin , write
Its count has a binomial distribution with parameters and . Across all bins, the counts jointly follow a multinomial distribution because each observation contributes to exactly one interval.
For an equal-width bin of width , the density estimate is . Its expected value and variance are
for in that bin. Thus the estimator is unbiased for the average density across the bin, not generally for the density at each individual point. Where the true density changes rapidly, replacing it by a constant creates approximation error.
For a sufficiently regular density and a regular equal-width partition, the leading asymptotic mean integrated squared error has the form
The first term reflects sampling variance and the second squared approximation error. Balancing them gives an optimal width proportional to , explaining the sample-size dependence in the Scott and Freedman–Diaconis rules. The formula requires smoothness and integrability conditions; it is not an exact finite-sample identity.
For a fixed location in a regular region, consistency generally requires widths to shrink while expected local counts grow. In one dimension, the familiar conditions are
The first permits increasing resolution, while the second prevents bins from becoming too sparse. A fixed bin width does not recover an arbitrarily detailed density as the sample grows; it estimates increasingly accurately the probabilities of the fixed intervals.
Histogram heights are also uncertain. Under the independent-sampling model, a count-based plug-in estimate of the standard error of a density height is
This approximation can be poor for sparse or empty bins. Moreover, heights in different bins are not independent: assigning an observation to one bin excludes it from the others. A collection of pointwise intervals is therefore not automatically a simultaneous confidence statement about the whole density. Dependence, unequal sampling probabilities, and data-selected boundaries require further adjustments.
Historical development and statistical graphics
The histogram developed within a broader nineteenth-century expansion of statistical tables, measurement, and graphical analysis. Grouped frequency distributions were used to organize observations before the modern terminology became established. Representing numerical intervals by adjacent rectangles linked tabulation with geometric ideas of area, allowing distributions to be compared visually rather than only through columns of counts.
Karl Pearson introduced the term histogram in statistical writing in 1895. His work belonged to the early development of mathematical statistics, in which empirical frequency distributions were compared with theoretical curves. The new terminology did not mean that all related forms of grouped-frequency graphics originated at that moment. The historical distinction between naming a device and developing its graphical antecedents is important.
Frequency curves and histograms served complementary purposes. A histogram retained a visible connection to grouped observations, while a smooth curve expressed a theoretical model or an approximation to the observed shape. Early statistical work on biological variation and other measured characteristics made this relationship especially significant: data could be displayed as a frequency distribution and then assessed against a proposed family of mathematical curves.
During the twentieth century, the histogram became a standard component of statistical teaching, industrial quality analysis, and scientific reporting. Sturges’s 1926 rule formalized one practical way to select the number of classes. Later research increasingly treated bin selection as a problem in estimation rather than merely page layout. Scott’s 1979 analysis and the 1981 work of Freedman and Diaconis connected a familiar graphical tool to explicit error criteria and asymptotic theory.
The development of exploratory data analysis, associated especially with John Tukey’s 1977 book of that title, encouraged attention to patterns, unusual observations, transformations, and alternative displays before imposing a statistical model. Within that approach, a histogram was valuable not as a definitive picture but as one representation whose construction could be varied to expose different aspects of the data.
Computing changed both the scale and the immediacy of histogram use. Hand-drawn displays required counts to be tabulated and intervals selected in advance. Statistical software made it straightforward to vary widths, compare subgroups, and process millions of observations. Interactive graphics extended this further by allowing bins to respond to filters and selections. At the same time, automated defaults made substantive decisions less visible: two programs could display noticeably different histograms of the same data simply because they selected different bins or normalization conventions.
Relationship to other distribution displays
A histogram differs from a bar chart primarily in what the horizontal positions represent. A bar chart compares distinct categories, whose ordering may be arbitrary or chosen for presentation. A histogram partitions a numerical axis into intervals with meaningful locations and widths. Gaps between categorical bars are conventional; gaps between occupied histogram bins can indicate an interval containing no observations. Visual resemblance alone does not determine which interpretation applies.
An empirical distribution function displays the fraction of observations less than or equal to each value:
It requires no bin width and preserves the exact order information needed to read empirical cumulative probabilities and quantiles. Its staircase structure avoids the histogram’s grouping choices, although local peaks and valleys are usually less immediately apparent. A density histogram, when integrated, instead produces a piecewise-linear cumulative distribution function corresponding to a uniform allocation of probability within each bin.
A frequency polygon joins heights plotted at bin centers. It can make several grouped distributions easier to compare on the same axes, but it still depends on the original binning. Connecting points also introduces an impression of linear change between centers that was not directly observed. It should therefore be understood as another representation of grouped information rather than a recovery of within-bin detail.
Kernel density estimation replaces fixed rectangles with smooth contributions centered on individual observations. A common estimator is
where is a kernel and a bandwidth. It avoids dependence on a single grid origin but introduces choices of kernel, smoothing bandwidth, and boundary treatment. Smoothness is a representational property, not evidence that a curve is more faithful to the population. An unsuitable bandwidth can create or erase apparent modes just as unsuitable histogram bins can.
Box plots, dot plots, and raw-data strip plots emphasize different information. A box plot gives a compact account of central location and spread but can conceal multimodality. Dot plots retain individual observations and are particularly informative for small samples. Quantile–quantile plots compare distributions through corresponding quantiles and can reveal departures from a reference model more clearly than an overlaid histogram curve.
When several populations are compared, their histograms need common edges to make interval-by-interval comparisons direct. Relative frequencies or densities separate shape from sample size, whereas counts preserve differences in total volume. Neither normalization is inherently preferable: the relevant choice depends on whether the subject is distributional shape, total activity, or both.
Weighted, adaptive, and multidimensional histograms
A weighted histogram assigns observation a nonnegative weight , rather than counting every observation equally. The weighted bin total is
With total weight , the density height is . The resulting area is one, but it describes the weighted distribution rather than the unweighted sample. Weights may represent repeated observations, exposure, population expansion factors, or numerical importance weights; those interpretations have different implications for uncertainty.
Survey weights, for example, may allow observations from differently sampled groups to represent their population proportions. The weighted histogram can then differ substantially from a histogram of the raw sample counts. However, treating the sum of weights as an ordinary sample size generally does not provide a valid variance calculation. Sampling design, clustering, and variation in weights can all affect precision.
Unequal-width or adaptive bins allocate resolution unevenly. Narrow bins may be used where observations are dense and wide bins where they are sparse. Equal-count bins, formed from empirical quantiles, have approximately equal probability mass. Their density heights vary inversely with their widths, so narrow intervals indicate concentration. Tied observations can prevent exact equal counts or produce repeated quantile boundaries that must be handled explicitly.
For paired observations, a two-dimensional histogram divides the plane into rectangular cells. If cell has count , horizontal width , and vertical width , its density estimate is
Color or shading commonly represents counts or density. Such a display approximates a joint distribution and can reveal concentrations and nonlinear relationships that separate one-dimensional histograms cannot. Summing cell counts across one coordinate gives marginal counts, provided the grids and included observations are consistent.
The extension to dimensions partitions space into cells whose volumes replace interval widths. This creates a direct form of the curse of dimensionality. With ten bins along each of six coordinates, there are possible cells. Even a large sample can leave most cells empty, making a fine joint histogram statistically unstable and difficult to store.
Multidimensional histograms also depend on coordinate orientation. A narrow diagonal concentration can intersect many axis-aligned cells even though the underlying structure is simple. Transformations or principal component analysis may produce a more compact representation, but they change the coordinates in which density is expressed. A joint histogram describes its specified partition, not a coordinate-free property of the dataset.
Algorithms, storage, and numerical implementation
For equal-width bins, computing a histogram is usually a single-pass operation. Given origin and width , an observation is assigned a provisional bin index
followed by checks for the allowed range and endpoint conventions. With fixed bins, the counting step takes time and storage in asymptotic notation. For arbitrary sorted edges, binary search finds a bin in time per observation. Sorting observations is not required merely to count fixed intervals.
The full procedure can require more than one pass if the boundaries depend on the data. Minimum and maximum values, standard deviation, or quartiles may have to be obtained before counting begins. Some summaries can be updated incrementally, while exact quantiles generally require retaining more information or using a suitable data structure. Streaming systems often use approximate quantile summaries or maintain histograms on predefined ranges.
Histograms with identical edges and compatible weights are straightforward to merge: corresponding counts are added. This makes them useful in parallel computing, where different processors or machines handle separate portions of the data. Exact merging requires agreement about edges, endpoint conventions, excluded values, and units. Histograms built on incompatible partitions cannot generally be converted to a common fine partition without the original observations.
Rebinning illustrates the information lost through aggregation. Adjacent fine bins can be combined exactly when the new boundaries coincide with existing edges. Splitting an existing bin is not exact because the positions of its observations are unknown. Allocating its count proportionally to subinterval lengths assumes a uniform distribution within that bin. Such an operation creates an approximation rather than recovering discarded information.
Floating-point arithmetic can complicate boundary assignment. A value displayed as a decimal boundary may be stored slightly above or below it, and repeated additions of a decimal width can accumulate rounding error. Robust implementations use consistent edge construction and explicit inclusion rules. The final edge often receives special treatment so that the maximum included value is not accidentally dropped.
Missing values, infinities, and out-of-range observations need separate policies. Silently removing them can change both the sample size and the meaning of a normalized display. Large datasets also require sufficiently wide integer counters to avoid overflow; weighted accumulation can incur floating-point error.
A histogram is a compact, deliberately lossy representation. Once only its bin counts remain, exact quantiles, individual extremes within bins, and the observation sequence may no longer be recoverable. This storage economy explains its computational usefulness and the limits of subsequent analysis based solely on the aggregated result.
Scientific, industrial, and image-processing applications
In industrial measurement, histograms describe distributions of dimensions, filling quantities, operating times, and other process outputs. A histogram can show whether observed values concentrate near a target, spread toward specification limits, or form separate groups. Specification limits are externally defined requirements, not features estimated from the histogram itself. A pooled histogram can also hide process changes over time, so its distributional information differs from that supplied by a chronological process chart.
In physics and spectroscopy, instruments often accumulate event counts into channels corresponding to measured energy, wavelength, or another quantity. A peak may reflect a physical emission feature broadened by the measurement system. Bin width, instrument resolution, calibration, and background counts all contribute to the observed form. Finer digital channels do not by themselves improve the instrument’s physical resolving power.
Count uncertainty is particularly important in such applications. Under a Poisson counting model, a count is often assigned an approximate uncertainty of when the count is sufficiently large and the model applies. This differs from the fixed-total multinomial model used for a sample distributed among bins. The appropriate model depends on how observations were collected: a fixed observation period with a fluctuating number of events is not identical to a fixed number of sampled events.
Digital images provide a different use. A grayscale image histogram records how many pixels occupy each intensity level; an 8-bit grayscale image has 256 possible codes, from 0 to 255. Such a histogram describes tonal allocation but discards spatial arrangement. Images with completely different objects and textures can have identical intensity histograms. Separate color-channel histograms similarly omit much of the joint information linking channels within individual pixels.
Histogram equalization uses a cumulative intensity distribution to construct a tonal transformation. Ideally, mapping an intensity through its cumulative probability redistributes mass across the output range. In discrete images, however, repeated input levels map together, so the resulting histogram need not be perfectly uniform. Local variants apply related transformations within image regions, often with constraints intended to limit excessive contrast amplification.
Histograms also support computational summaries of entropy and distributional discrepancy. For bin probabilities , the discrete entropy is . This is the entropy of the binned variable, not automatically the differential entropy of an underlying continuous quantity. Its value changes with binning. Likewise, a histogram-based Kullback–Leibler divergence depends on common boundaries and can become infinite when one distribution assigns positive mass to a bin assigned zero mass by the other. Smoothing or pseudocounts alter that calculation and constitute additional modeling choices.