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:
datais the list or array of numeric values.binscontrols how many groups (bars) the data is split into.colorsets the color of the bars.alphacontrols 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:
| Parameter | Description | Example |
|---|---|---|
| data | Numeric data array to plot | [1, 2, 3, 4, 5] |
| bins | Number of bars or bin edges | 10 or [0,5,10,15] |
| color | Bar color | 'blue', '#FF5733' |
| alpha | Transparency level (0 to 1) | 0.5 |
| edgecolor | Color of bar edges | 'black' |
| density | Normalize histogram to form a probability density | True 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.