0
0
MatplotlibHow-ToBeginner ยท 3 min read

How to Create Histogram in Matplotlib: Simple Guide

To create a histogram in matplotlib, use the plt.hist() function with your data array as input. This function automatically groups data into bins and displays the frequency distribution as bars.
๐Ÿ“

Syntax

The basic syntax for creating a histogram in Matplotlib is:

  • plt.hist(data, bins, color, alpha)

where:

  • data is the list or array of numeric values.
  • bins controls how many groups (bars) the data is split into.
  • color sets the color of the bars.
  • alpha controls the transparency of the bars (0 to 1).
python
import matplotlib.pyplot as plt

plt.hist(data, bins=10, color='blue', alpha=0.7)
plt.show()
๐Ÿ’ป

Example

This example shows how to create a histogram of 100 random numbers between 0 and 50, split into 10 bins. It demonstrates how the data is grouped and displayed as bars.

python
import matplotlib.pyplot as plt
import numpy as np

# Generate 100 random numbers from 0 to 50
data = np.random.randint(0, 51, 100)

# Create histogram with 10 bins
plt.hist(data, bins=10, color='green', alpha=0.6)
plt.title('Histogram of Random Numbers')
plt.xlabel('Value Range')
plt.ylabel('Frequency')
plt.show()
Output
A histogram plot window showing 10 green bars representing frequency counts of random numbers in each range.
โš ๏ธ

Common Pitfalls

Common mistakes when creating histograms include:

  • Not specifying bins, which can lead to too few or too many bars.
  • Passing non-numeric data, causing errors.
  • Forgetting to call plt.show() to display the plot.
  • Using inappropriate transparency or colors that make bars hard to see.

Example of a wrong and right way:

python
# Wrong: No bins specified, default may not suit data
plt.hist(data)
plt.show()

# Right: Specify bins for clearer grouping
plt.hist(data, bins=15)
plt.show()
๐Ÿ“Š

Quick Reference

Here is a quick reference for plt.hist() parameters:

ParameterDescriptionExample
dataNumeric data array to plot[1, 2, 3, 4, 5]
binsNumber of bars or bin edges10 or [0,5,10,15]
colorBar color'blue', '#FF5733'
alphaTransparency level (0 to 1)0.5
edgecolorColor of bar edges'black'
densityNormalize histogram to form a probability densityTrue or False
โœ…

Key Takeaways

Use plt.hist() with your numeric data to create a histogram easily.
Specify bins to control how data groups into bars for better clarity.
Always call plt.show() to display the histogram plot.
Avoid non-numeric data and choose colors and transparency for clear visuals.
Use parameters like edgecolor and density to customize the histogram appearance.