Visualizing Data Distributions with Matplotlib‘s pyplot.hist() in Python

Histograms are one of the most fundamental tools in a data scientist‘s visualization toolkit. By displaying the distribution of a dataset, histograms provide valuable insights into the shape and spread of the data that can inform further analysis. And with Python‘s matplotlib library, creating publication-quality histogram visualizations is only a few lines of code away using the pyplot.hist() function.

In this in-depth guide, we‘ll cover everything you need to know to master pyplot.hist() and create impressive histograms from your own data. We‘ll start with the basics of what histograms represent and why they are useful, then dive into detailed code examples demonstrating the key parameters and more advanced features. By the end, you‘ll be able to easily visualize the distribution of any dataset using Python and matplotlib!

Understanding Histograms

Before we get into the code, let‘s make sure we understand exactly what a histogram is visualizing. A histogram plots the frequency or count of data points that fall within discrete bins, or intervals, of the variable being measured. The x-axis represents the variable, divided into the bins, while the y-axis represents the count or frequency of data points within each bin.

For example, say we have a dataset of the heights (in inches) of 1000 people. To create a histogram of heights, we would divide the range of heights into evenly spaced bins, say 0-10", 10-20", 20-30", etc. Then we would count how many people have a height that falls within each bin and plot those counts as bars.

The shape and spread of the bars on a histogram can instantly reveal a lot about the distribution of the data. A symmetric histogram with a single peak in the middle represents data that is normally distributed (i.e. bell curve). An asymmetric histogram with a long tail on one side indicates the data is skewed in that direction. Gaps in the bars or multiple peaks may suggest the data contains distinct sub-groups.

This ability to quickly visualize and comprehend the distribution of a variable makes histograms an invaluable tool during exploratory data analysis for data scientists. Now let‘s see how to easily plot them in Python using matplotlib!

Basic Usage of pyplot.hist()

The pyplot.hist() function in matplotlib makes it very simple to plot a histogram in just a couple lines of code. Here is the basic syntax:

import matplotlib.pyplot as plt

data = [1, 1, 2, 3, 4, 5, 5, 5, 6, 6, 7, 8, 8, 9 , 10]

plt.hist(data)
plt.show()

Executing this code produces the following histogram:

Basic histogram

By default, pyplot.hist() makes a pretty good histogram right out of the box by automatically choosing a reasonable number of bins based on the data provided. However, it offers a number of parameters we can tweak to customize our histogram as needed. The three you‘ll use most often are:

  • bins: Number of bins (intervals) or the actual bin edges
  • range: Tuple of (min, max) for the x-axis range to plot
  • density: Boolean to plot counts (False) or probability density (True)

Here‘s an example using those parameters:

plt.hist(data, bins=5, range=(0, 10), density=True) 

Customized histogram

Now the histogram has only 5 evenly spaced bins spanning 0-10 on the x-axis, and the y-axis shows the probability density instead of raw counts.

Adjusting Histogram Appearance

In addition to tweaking the histogram parameters, pyplot.hist() also accepts standard arguments for modifying the appearance of the plot elements themselves, like fill color, edge color, opacity, labels, titles, and more.

plt.hist(data, bins=5, range=(0, 10), density=True,
         color=‘skyblue‘, edgecolor=‘black‘, alpha=0.7)

plt.xlabel(‘Value‘)
plt.ylabel(‘Density‘) 
plt.title(‘Histogram of Data‘)
plt.show()

Styled histogram

Here we made the histogram bars sky blue with a black outline and 70% opacity. We also added proper labels for the x/y axes and a title above the plot. Small tweaks like this can make a big difference in the polish and professionalism of your visualizations.

Plotting Multiple Histograms

Often we want to compare the distributions of more than one group or variable at a time. This can be done by plotting multiple histograms together, either side-by-side or overlapping.

To plot separate histograms in the same figure, use the plt.subplots() function to create a figure with a grid of subplots, then call plt.hist() on each one:

data1 = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5]
data2 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,4))

ax1.hist(data1, bins=5, alpha=0.7)
ax1.set_title(‘Data 1‘)
ax1.set_xlabel(‘Value‘) 
ax1.set_ylabel(‘Frequency‘)

ax2.hist(data2, bins=5, alpha=0.7)
ax2.set_title(‘Data 2‘) 
ax2.set_xlabel(‘Value‘)
ax2.set_ylabel(‘Frequency‘)

plt.tight_layout()
plt.show()

Multiple histograms

Each histogram is plotted in its own subplot object (ax1 and ax2) which can be customized independently just like a regular plot. The plt.tight_layout() function at the end automatically adjusts the spacing between subplots to avoid overlap.

To plot overlapping histograms for more of a direct comparison, simply call plt.hist() multiple times before the final plt.show():

plt.figure(figsize=(6,4))

plt.hist(data1, bins=5, alpha=0.5, label=‘Data 1‘)
plt.hist(data2, bins=5, alpha=0.5, label=‘Data 2‘)

plt.legend()
plt.show()

Overlapping histograms

Using a semi-transparent alpha value between 0-1 allows the histograms to be visible through each other. The plt.legend() function then automatically generates a legend to distinguish them.

Alternative Histogram Styles

For a different look than the default bar-style histogram, pyplot.hist() provides a few alternative styles via the "histtype" parameter:

  • ‘bar‘: Traditional rectangular bars (default)
  • ‘step‘: Unfilled line plot
  • ‘stepfilled‘: Line plot with area underneath filled

For example:

plt.figure(figsize=(8,4))

plt.subplot(1,2,1)
plt.hist(data, bins=10, histtype=‘step‘)

plt.subplot(1,2,2)  
plt.hist(data, bins=10, histtype=‘stepfilled‘, alpha=0.5)

plt.tight_layout()
plt.show()

Histogram styles

The ‘step‘ style can be useful for plotting multiple dense histograms together, while ‘stepfilled‘ provides a nice middle ground between ‘step‘ and the original ‘bar‘ style.

Histogram Best Practices

When creating histograms to visualize your own data, keep these tips in mind:

Choose an appropriate number of bins. Too few bins will oversimplify the distribution and hide key features, while too many bins will be noisy and hard to interpret. There are statistical formulas to determine the optimal bin size, but generally aim for between 5-20 bins depending on the data.

Always label your axes and provide a meaningful title. Histograms are easy to misinterpret without proper context about what data is being plotted.

Use a density plot if comparing groups of different sizes. Density normalizes the counts to a percentage so the bar heights are comparable even if the number of data points differs between groups.

Consider a log scale if the data covers a very wide range of values. This will help spread out the bars more evenly instead of bunching up on one end.

When to Use Histograms vs. Other Plots

Histograms are the go-to plot for visualizing the distribution of a single variable, but there are some situations where other plot types may be more appropriate:

Bar plots are better for displaying the frequency of categorical variables rather than numeric variables. The bars represent counts of each category rather than binned ranges of continuous numbers.

Box plots are an alternative for comparing the distributions of multiple groups in less space than individual histograms. They don‘t show the full shape of the distribution but helpfully plot key metrics like the median, quartiles, and outliers.

Density plots are similar to histograms but use kernel smoothing to plot a continuous curve of the distribution rather than discrete bins. This makes them better for very large datasets.

Additional Resources

Official matplotlib hist documentation: https://matplotlib.org/3.2.1/api/_as_gen/matplotlib.pyplot.hist.html

Matplotlib histogram tutorial: https://www.tutorialspoint.com/matplotlib/matplotlib_histogram_plot.htm

In-depth overview of histograms and their uses: https://towardsdatascience.com/understanding-and-interpreting-histograms-in-python-e4c852edfb73

When to use a histogram vs. bar chart: https://www.forbes.com/sites/naomirobbins/2012/01/04/a-histogram-is-not-a-bar-chart/

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

Similar Posts