Histograms
DS 2023 | Communicating with Data

Overview¶
A histogram is a special case of a bar plot designed for visualizing the statistical properties of a variable.
It has the following properties:
On the x axis, a numerical feature is converted into a category (in effect) by binning.
The numeric bins are represented in ascending order.
On the y axis is displayed the frequency of the observations for each bin.
The bars are usually depicted contiguously, i.e. adjacent bars touch. Bar charts typically show separation between bars.
Use cases¶
Histograms provide a quick way to inspect the centrality and dispersion of a distribution.
They also allow you to inspect the shape of a distribution for modality, skew, and kurtosis.
They can be used to surface outliers and mutliple populations.
Histograms are frequently used to represent the distributions of measurements among a population, such as the height of people or the grades of students in a class. It shows how many cases have a certain measurement.
Creating a histogram from scratch¶
Let’s build a histogram so that we may better understand its properties.
Consider the following data set of yearly life expectancy rates and healthcare costs for a set of countries.
The two numeric features are good candidates for a histogram since they are ratio measures.
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import seaborn as snshealthexp = sns.load_dataset('healthexp')
healthexp = healthexp.set_index(['Year','Country'])
healthexp.sample(10)Let’s focus on life expectancy, expressed as age, where we’d expect a gaussian distribution.
If we convert the continous numbers for age to discrete integers, we can treat age as a category to group on.
We can get the value counts by age and display them as a bar chart.
(
healthexp
.Life_Expectancy
.astype(int)
.value_counts()
.sort_index()
.plot.bar(rot=0)
)
plt.show()
Note that we have to sort the index since .value_counts() sorts by count and we need the age categories to be in sequential order.
Now, to meet the design requirements of a histogram, we can adjust the width of the bars to make them touch.
We do this by setting width = 1.
healthexp.Life_Expectancy.astype(int).value_counts().sort_index().plot.bar(width=1, rot=0)
plt.show()
In this example, we have created a bin for age value based on their integer value.
We might adjust this by grouping ages into groups of 5 or 10 years.
Or we could decide how many bins we want and use pd.cut() to create them, like so:
n_bins = 20
(
pd.cut(healthexp.Life_Expectancy, n_bins)
.value_counts()
.sort_index()
.plot.bar(width=1)
)
plt.show()
This is good, but the x axis is difficult to read.
More important, it will change with each change of the parameter n_bins.
n_bins = 40
(
pd.cut(healthexp.Life_Expectancy, n_bins)
.value_counts()
.sort_index()
.plot.bar(width=1)
)
plt.show()
Bar height¶
There is a second thing that changes with n_bins: the height of the bars.
So far, our y axis has shown counts, the number of observations in each bin.
But there are two other ways to scale the y axis:
A proportion is a count divided by the total number of observations, so the bars sum to 1.
A density is a proportion divided by the width of the bin, so the areas of the bars sum to 1.
Let’s compute all three from the bins we just made.
Because pd.cut() makes bins of equal width, the width of each bin is just the range of the data divided by n_bins.
bins = pd.cut(healthexp.Life_Expectancy, n_bins)
bin_width = (healthexp.Life_Expectancy.max() - healthexp.Life_Expectancy.min()) / n_bins
y_axis = bins.value_counts().sort_index().to_frame('count')
y_axis['proportion'] = y_axis['count'] / y_axis['count'].sum()
y_axis['density'] = y_axis['proportion'] / bin_width
print(f"Bin width: {bin_width:.3f} years")
y_axis.round(3)Bin width: 0.353 years
Let’s check the two claims above.
print("Sum of proportions:", y_axis['proportion'].sum())
print("Total area of density bars:", (y_axis['density'] * bin_width).sum())Sum of proportions: 1.0
Total area of density bars: 1.0
As we expected, both the bars and the areas sum to 1.
Now let’s plot all three side by side.
fig, ax = plt.subplots(1, 3, figsize=(12, 3))
for i, col in enumerate(y_axis.columns):
y_axis[col].plot.bar(width=1, ax=ax[i], title=col, xticks=[])
ax[i].set_xlabel('Life_Expectancy bins')
plt.tight_layout()
plt.show()
The three histograms have exactly the same shape.
Only the scale of the y axis changes.
Using Pandas’ histogram function¶
So, we see how a histogram is constructed.
Panda’s histogram method .plot.hist() does all this work for us and adds some nice formatting touches.
To use it, we give it a measurement variable and pass it the number of bins by which we want to group the observations.
The default value is 10.
Here we choose 20 to mirror our from-scratch version.
healthexp.Life_Expectancy.plot.hist(bins=n_bins)
plt.show()
Notice how the histogram function represents the x and y axes:
The x axis is represented as a continuum, even though the bars themselves are discrete.
This allows the axis to remain true to the feature domain it represents
It also remains unchanged as the
binsargument changes.The y axis is now labeled “Frequency”. Frequency here means count.
It is common to represent the bars with borders, which we can accomplish as follows.
healthexp.Life_Expectancy.plot.hist(
bins=n_bins, edgecolor='lightblue', linewidth=1.2)
plt.show()
Showing density¶
Pandas can put the y axis on a density scale for us with density=True.
healthexp.Life_Expectancy.plot.hist(
bins=n_bins,
density=True)
plt.show()
Notice the changes in the y axis.
The scale has changed.
It still labels the axis “Frequency”, though, which is not quite right.
Why is setting density=True useful?
To see, let’s draw the same variable with 10 bins and with 40 bins, first as counts and then as densities.
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
for n in [10, 40]:
healthexp.Life_Expectancy.plot.hist(bins=n, alpha=.5, ax=ax[0], label=f'{n} bins', title='Counts')
healthexp.Life_Expectancy.plot.hist(bins=n, alpha=.5, ax=ax[1], label=f'{n} bins', title='Densities', density=True)
ax[0].legend()
ax[1].legend()
ax[1].set_ylabel('Density')
plt.tight_layout()
plt.show()
With counts, the two histograms sit on different scales.
Wider bins catch more observations, so their bars are taller.
With densities, the two histograms sit on the same scale.
Dividing by the bin width cancels the effect of the bin count.
In the comparisons above, it may appear odd that the number of bins can so drastically affect the area of the histogram.
It is reasonable to ask, shouldn’t the total area of the bars be the same regardless of bin size?
The reason the blue shaded area looks so much larger than the orange is that the visual width of the bar per bin is larger.
If we set them to be about the same, as below, we can see that for each interval, the shorter orange bars stack up to the height of the taller blue bars.
By keeping the visual bin width constant, we lose the misleading effect of one histogram covering more area than the other.
vis_bin_width = .33
healthexp.Life_Expectancy.plot.hist(bins=10, alpha=.25, label='10 bins', title='Counts', width=vis_bin_width)
healthexp.Life_Expectancy.plot.hist(bins=40, alpha=.25, label='40 bins', title='Counts', width=vis_bin_width)
plt.show()
Showing populations¶
As we might imagine, the distributions of life expectancy ages vary by country.
To visualize this, we can group the age variable by nation and show each histogram separately.
We can achieve this effect by creating a wide table in which Country is projected onto the column, and Year the row axis (or index), and the values come from Life_Expectancy.
life_exp_wide = healthexp['Life_Expectancy'].unstack()
life_exp_wide.head()Passing this wide-form dataframe to the histogram method produces the following composite figure:
life_exp_wide.plot.hist(alpha=.25)
plt.show()
Here we can see that this histogram we created above masked the fact that the underlying data contained many populations.
To better visualize the differences among these populations, we have a couple of options.
One option is to stack the bars, as in a stacked bar chart.
life_exp_wide.plot.hist(stacked=True, width=.9)
plt.show()
Or, we can break out each country using subplots.
life_exp_wide.plot.hist(subplots=True, figsize=(5, 10), sharey=True)
plt.tight_layout()
plt.show()
Histograms in exploratory data analysis¶
The histogram is often the first plot drawn on a new numeric measurement variable.
This is because summary statistics, like mean and standard deviation, don’t tell use the whole story, as we learned from Anscombe’s Quartet.
Here are some tasks we use histograms for in exploratory data analysis to get a more complete understanding of a variable:
Checking whether a summary statistic means anything¶
The mean of Life_Expectancy is 77.9 and its median is 78.1.
These figures are consistent with a roughly normal distribution, and a report that gave only those numbers would imply one.
But the subplots above show that the feature is a mixture of six populations.
The value 77.9 falls between them and describes none of them.
Deciding whether to transform a feature¶
Skew is visible in a histogram immediately.
Spending_USD has a skew of 1.30, and a mean of 2789 against a median of 2296.
The histogram shows the long right tail that accounts for the difference.
When you see all the data bunched up to the left of the right, you may want to rescale the data logarithmically.
This is similar to what we saw with scatter plots and hexbin plots.
Here we get the log of the variable and then plot it.
This opens up the bunched up data to better expose patterns.
fig, ax = plt.subplots(1, 2, figsize=(12, 4))
healthexp.Spending_USD.plot.hist(bins=25, ax=ax[0], title='Spending_USD')
healthexp.Spending_USD.apply(np.log).plot.hist(bins=25, ax=ax[1], title='Log')
plt.tight_layout()
plt.show()
Assessing coverage and completeness¶
A histogram of a grouping variable, rather than of a measurement, reports how the dataset itself is populated.
We can use it to see if our data are balanced.
healthexp.reset_index().Year.plot.hist()
plt.title('Observations per year')
plt.xlabel('Year')
plt.show()
We can see that the bars rise through the 1970s and 1980s and level off in the mid 1990s.
This means that healthexp is unbalanced.
On closer inspection of the data, we can see that of its 51 years, 32 have all six countries and five have only three.
This is the same fact that produced the NaN values in the wide table above.
The consequence is that any statistic computed across all rows weights the later years more heavily, because more countries report in them.
Detecting multiple populations¶
This is the task demonstrated in the previous section.
The pooled histogram of Life_Expectancy is unremarkable.
Broken out by country, it resolves into six distributions with different locations and ranges.
Finding data quality problems¶
Several kinds of defect are visible in a histogram and invisible in the summary statistics:
Spiking. A spike at 0, -1, or -999 usually marks missing data that was never converted to
NaN.Heaping. Spikes at multiples of 5 or 10 indicate rounding or self-reporting rather than measurement.
Censoring. A pile-up in the first or last bin suggests the feature was capped, as with top-coded income.
Gaps. An empty interval in the middle of a range suggests that a filter was applied upstream.
healthexp exhibits none of these, which is worth confirming rather than assuming.
Choosing a bin value¶
In a histogram, the bin count is itself an exploratory parameter.
It determines the resolution of the plot.
Too few bins conceal structure, and too many resolve sampling noise into apparent features.
One under fits the data, the other over fits it.
In other words, you have to play with it to find the most useful value.
This dependence on binning is one of the motivations for the density plot, which is the subject of the next lesson.