Relative Frequency
Descriptive Statistics
From Counts to Proportions — The Bridge to Probability
Relative frequency converts raw counts into proportions, revealing how often each category occurs relative to the whole. It is the empirical bridge between data and probability.
- Probability estimation — Use observed proportions as estimates of true probabilities
- Cross-dataset comparison — Compare distributions of different sizes on equal footing
- Law of Large Numbers — Relative frequency converges to true probability as n grows
- Foundation for histograms — Density histograms use relative frequency on the y-axis
When you divide every count by the total, you unlock the connection between data and probability.
What You'll Learn
- 1Compute relative, cumulative, and conditional relative frequencies from a contingency table
- 2Explain why the relative frequencies of all categories sum to exactly one
- 3Quantify the uncertainty of a relative frequency estimate at a given sample size
- 4Choose between counts, proportions, and densities when plotting a distribution
What Is Relative Frequency?
Definition
Relative frequency is the proportion (or percentage) of times a value occurs in a dataset compared to the total number of observations. It estimates the probability of that category.
The operation is a single division, but what it buys is substantial. Counts are tied to the size of the sample that produced them: 40 failures out of 200 and 400 failures out of 2,000 look identical as raw numbers and mean very different things. Dividing by the total puts every dataset on a common scale where 0.20 means 0.20 regardless of how many observations went into it, which is what makes a comparison between a pilot study and a national survey possible at all.
Two structural properties follow immediately and are worth checking whenever you build a frequency table by hand. Every relative frequency lies between 0 and 1 inclusive, and the sum over all categories is exactly 1. The second property is not a coincidence: it says the relative frequencies of a categorical variable form a valid probability mass function, and it is the reason a column of proportions that adds to 0.97 signals a dropped category or a rounding problem rather than a minor blemish.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
np.random.seed(42)
# Generate sample data
colors = np.random.choice(['Red', 'Blue', 'Green', 'Yellow'], size=100, p=[0.3, 0.25, 0.25, 0.2])
# Compute relative frequencies
value_counts = pd.Series(colors).value_counts()
relative_freq = value_counts / len(colors)
print("Absolute and Relative Frequencies:")
print(pd.DataFrame({
'Count': value_counts,
'Relative Frequency': relative_freq.round(4),
'Percentage': (relative_freq * 100).round(1).astype(str) + '%'
}))
| Category | Count | Relative frequency | Percentage | Cumulative |
|---|---|---|---|---|
| Red | 30 | 0.30 | 30% | 0.30 |
| Blue | 25 | 0.25 | 25% | 0.55 |
| Green | 25 | 0.25 | 25% | 0.80 |
| Yellow | 20 | 0.20 | 20% | 1.00 |
pandas sorts by count by default, so the table above is ordered by frequency. Pass sort=False to preserve the order the categories appear in the data, which matters when the categories are ordinal — growth, flat, decline should never be reordered by how often they occurred.
Cumulative Relative Frequency
The running total of the proportions answers "at or below" questions directly:
# Cumulative relative frequency
cumulative_freq = relative_freq.cumsum()
print("\nCumulative Relative Frequency:")
print(cumulative_freq.round(4))
Read the last non-unit entry of that column to find the quantiles: the point where the cumulative proportion first crosses 0.50 is the sample median, and the crossing points of 0.25 and 0.75 give the quartiles. For grouped or binned data the crossing is interpolated between bins, which is the only place where a shape assumption — usually linear interpolation — enters an otherwise assumption-free calculation.
Conditional Relative Frequencies
A single proportion becomes far more informative once the denominator is chosen deliberately. In a two-way table, dividing each cell by its row total gives row percentages, which describe the distribution of the outcome within each group; dividing by the column total gives column percentages, which describe the composition of each column. The two answer different questions and are routinely confused.
Suppose 120 of 500 men and 90 of 500 women prefer a product. The overall relative frequency of preference is 210/1000 = 0.21. The row-relative rates are 120/500 = 0.24 for men and 90/500 = 0.18 for women, and their difference of 0.06 is the quantity a chi-square test or a two-proportion z-test would evaluate. Reporting only the pooled 0.21 hides the comparison entirely.
Estimating Probability From Data
Treating a relative frequency as an estimate of a probability means accepting an error bar. For a proportion computed from independent observations, the standard error is , and the interval is the usual 95 percent approximation.
At with the standard error is 0.046, giving a margin of roughly ±0.09 — the honest reading is "somewhere between 21 and 39 percent". At the standard error falls to 0.0046 and the margin to ±0.009. The rate of improvement follows the square root of the sample size, so cutting the error in half costs four times the data. This is why a category observed 3 times out of 50, a relative frequency of 0.06, carries a confidence interval wide enough to include almost any plausible rate.
To check whether observed proportions match a claimed distribution, use the chi-square goodness-of-fit statistic with degrees of freedom, where the expected counts are the claimed probabilities times . Large deviations relative to the expected counts push the statistic into the tail and contradict the claim.
Visualization
fig, axes = plt.subplots(1, 2, figsize=(12, 5))
# Bar chart of relative frequencies
relative_freq.plot(kind='bar', color=['#e74c3c', '#3498db', '#2ecc71', '#f39c12'], ax=axes[0])
axes[0].set_title('Relative Frequency Distribution')
axes[0].set_ylabel('Relative Frequency')
axes[0].set_ylim(0, 0.4)
# Frequency polygon
relative_freq.plot(kind='line', marker='o', ax=axes[1])
axes[1].set_title('Frequency Polygon')
axes[1].set_ylabel('Relative Frequency')
plt.tight_layout()
plt.savefig('relative-frequency.png', dpi=150)
plt.show()
For continuous data the bar chart becomes a histogram, and the vertical axis needs one extra decision. Plotting the raw relative frequency per bin makes the total height sum to 1, so changing the bin width changes how tall the bars look. Dividing each relative frequency by its bin width makes the total area sum to 1 instead, producing a density histogram whose shape is stable across bin widths. Any comparison between histograms with different binning requires the density form.
| Axis choice | Sums to | Use it when |
|---|---|---|
| Count | n | Single dataset, absolute sizes matter |
| Relative frequency | 1 | Comparing two datasets of different sizes |
| Relative frequency density | Area = 1 | Comparing histograms with different bin widths |
Relative Frequency in Machine Learning
| ML Application | Relative Freq Usage | Why |
|---|---|---|
| Class balance | Check target distribution | Detect imbalance |
| NLP | Word frequency (Zipf's law) | Tokenization strategy |
| Feature engineering | Frequency encoding | Replace categories with freq |
| Data validation | Expected vs observed proportions | Detect data drift |
import numpy as np
import pandas as pd
np.random.seed(42)
# Class imbalance detection
y = np.random.choice(['fraud', 'legit'], 10000, p=[0.02, 0.98])
freq = pd.Series(y).value_counts(normalize=True)
print("Relative frequency (class balance):")
print(freq.round(4))
print(f"\nFraud rate: {freq['fraud']:.2%} — extreme imbalance!")
print("Solutions: SMOTE, class weights, undersampling")
# Frequency encoding
categories = np.random.choice(['A', 'B', 'C', 'D'], 1000, p=[0.5, 0.3, 0.15, 0.05])
freq_map = pd.Series(categories).value_counts(normalize=True).to_dict()
encoded = [freq_map[c] for c in categories]
print(f"\nFrequency encoding: {freq_map}")
Class imbalance is a relative frequency question first: a 2 percent fraud rate means accuracy on a naive all-legit classifier is already 98 percent, so any metric built on raw counts must be replaced by precision, recall, or AUC. Frequency encoding converts a categorical feature into its relative frequency, which is compact and ordinal but leaks target information if computed on the full dataset instead of inside each cross-validation fold. Monitoring pipelines use the same arithmetic in reverse — comparing the relative frequencies of a feature in production against the training reference, where a shift beyond the expected standard error is a drift alarm rather than noise.
Common Mistakes
Comparing counts from datasets of different sizes
Fix: Divide by the total first. Forty complaints out of 200 and forty out of 5,000 are 20 percent and 0.8 percent, and only the relative frequency shows that.
Plotting relative frequencies per bin on a histogram with changing bin widths
Fix: Use relative frequency density — divide each proportion by its bin width — so the area of the histogram stays at one and shapes remain comparable.
Reporting a small-category proportion without its sample size or margin of error
Fix: Attach the standard error sqrt(p(1-p)/n). Three hits out of fifty is 6 percent with a 95 percent interval spanning roughly 1 to 17 percent.
Best Practices
- Verify that relative frequencies sum to one as a cheap integrity check on every frequency table
- Report the denominator alongside every proportion, because precision depends on it
- Compute frequency encodings inside cross-validation folds to avoid leakage
Key Takeaways
- Relative frequency is count divided by total, and the values across all categories sum to exactly 1
- Cumulative relative frequency turns into quantiles: the 0.50 crossing point is the median
- Uncertainty shrinks only as the square root of n, so 0.30 at n = 100 really means roughly 0.21 to 0.39
- Relative frequencies estimate probabilities, which is what makes them the frequentist foundation of probability itself
Frequently Asked Questions
Relative frequency and probability — what is the difference?
Probability is the long-run theoretical limit; relative frequency is what you observed in a finite sample. The law of large numbers says the second converges to the first as the sample grows, so relative frequency is used as an estimator of probability together with a standard error that quantifies how much trust the estimate deserves.
Why do relative frequencies always add up to one?
Because every observation is assigned to exactly one category, so the sum of the counts equals the total. Dividing that sum by the total leaves 1. A table that violates this has either unassigned observations, double-counted rows, or rounding that was never reconciled.
When should I use a frequency polygon instead of a bar chart?
A polygon connects the midpoints of the bars and makes the shape and any shifts between two overlaid distributions easier to see, especially for ordered categories where the sequence carries meaning. Bar charts remain preferable for unordered categories, because connecting unrelated categories with a line implies a continuity that does not exist.
Interview Questions
Q1: How do you estimate a probability from data and how precise is it?
Use the relative frequency as the point estimate and sqrt(p(1-p)/n) as the standard error. A 30 percent rate from 100 observations has a standard error of 0.046, so the 95 percent interval runs about 21 to 39 percent.
Q2: What is the difference between relative frequency and relative frequency density?
Relative frequency divides the count by the total so heights sum to one. Density additionally divides by the bin width so areas sum to one, which keeps the histogram's shape stable when you change the binning.
Q3: How does relative frequency relate to the law of large numbers?
The law states that the relative frequency of an event converges in probability to its true probability as n grows, at rate one over the square root of n. It is the justification for treating observed proportions as estimates.
Q4: Why is frequency encoding a useful feature and what is its main risk?
It maps a category to its observed proportion, giving a compact ordinal feature. Its risk is target leakage: computing the mapping on the full dataset lets information from the validation fold influence training, so it must be fit within each fold.