Histograms in Matplotlib
In this lesson, you will learn how to create histograms using Matplotlib. You will understand data distributions, bins, frequency, density, cumulative histograms, and histogram customization.
1. Learning Objectives
By the end of this lesson, you will be able to:
- Understand what a histogram is and where it is used.
- Create histograms using the hist() function.
- Understand bins, frequency, and data intervals.
- Customize histogram colours and borders.
- Control the number and width of bins.
- Create density and cumulative histograms.
- Compare multiple data distributions.
- Add titles, labels, legends, and grid lines.
- Save histograms in different file formats.
2. What Is a Histogram?
A histogram is a graphical representation that shows the distribution of numerical data. It divides data into intervals called bins and displays the frequency of values within each interval.
In Matplotlib, the hist() function is used to create histograms. Each bar represents an interval, and its height represents the number of observations in that interval.
Example: Student Exam Marks
Suppose a teacher wants to understand how students performed in an examination. Instead of displaying every student's marks separately, the teacher can group the marks into intervals such as 0–20, 20–40, 40–60, 60–80, and 80–100.
3. Basic Syntax of the hist() Function
The hist() function accepts numerical data and groups the values into intervals called bins.
Syntax
import matplotlib.pyplot as plt
plt.hist(data)
plt.show()
| Parameter | Description |
|---|---|
| data | Numerical values used to create the histogram. |
| plt.hist() | Creates a histogram from numerical data. |
| plt.show() | Displays the created histogram. |
4. Creating Your First Histogram
Let's create a histogram to understand the distribution of students' examination marks.
Example: Student Exam Marks
import matplotlib.pyplot as plt
marks = [
35, 40, 45, 50, 55,
60, 65, 70, 75, 80,
85, 90, 55, 65, 75,
45, 50, 60, 70, 80
]
plt.hist(marks)
plt.title("Distribution of Student Marks")
plt.xlabel("Marks")
plt.ylabel("Frequency")
plt.show()
Explanation:
- marks contains the examination marks of students.
- hist() groups the marks into intervals.
- The X-axis displays the mark intervals.
- The Y-axis displays the frequency of observations.
- title(), xlabel(), and ylabel() add chart information.
- show() displays the histogram.
5. Understanding Bins in a Histogram
Bins are intervals used to group numerical data. Each bin represents a range of values, and its height shows how many observations fall within that range.
Example: Changing the Number of Bins
import matplotlib.pyplot as plt
marks = [
35, 40, 45, 50, 55,
60, 65, 70, 75, 80,
85, 90, 55, 65, 75,
45, 50, 60, 70, 80
]
plt.hist(marks, bins=5, color="skyblue",
edgecolor="black")
plt.title("Histogram with 5 Bins")
plt.xlabel("Marks")
plt.ylabel("Frequency")
plt.show()
| Bins | Description |
|---|---|
| bins=5 | Divides the data range into five intervals. |
| bins=10 | Divides the data range into ten intervals. |
| bins=20 | Divides the data range into twenty intervals. |
6. Customizing Histogram Colours and Borders
You can customize a histogram using parameters such as color, edgecolor, alpha, and linewidth.
Example: Customized Histogram
import matplotlib.pyplot as plt
marks = [
35, 40, 45, 50, 55,
60, 65, 70, 75, 80,
85, 90, 55, 65, 75,
45, 50, 60, 70, 80
]
plt.hist(
marks,
bins=6,
color="mediumseagreen",
edgecolor="black",
alpha=0.8,
linewidth=1.5
)
plt.title("Customized Student Marks Histogram")
plt.xlabel("Marks")
plt.ylabel("Frequency")
plt.show()
| Parameter | Description | Example |
|---|---|---|
| color | Sets the fill colour of histogram bars. | color="green" |
| edgecolor | Sets the border colour of bars. | edgecolor="black" |
| alpha | Controls transparency. | alpha=0.8 |
| linewidth | Controls the border thickness. | linewidth=1.5 |
7. Understanding Frequency and Density
A frequency histogram displays the number of observations in each bin. A density histogram displays normalized values so that the total area under the histogram is equal to one.
Example: Density Histogram
import matplotlib.pyplot as plt
marks = [
35, 40, 45, 50, 55,
60, 65, 70, 75, 80,
85, 90, 55, 65, 75,
45, 50, 60, 70, 80
]
plt.hist(
marks,
bins=5,
density=True,
color="orange",
edgecolor="black"
)
plt.title("Density Histogram")
plt.xlabel("Marks")
plt.ylabel("Density")
plt.show()
8. Creating a Cumulative Histogram
A cumulative histogram displays the running total of observations as you move from one bin to the next. It helps understand how many values fall below a particular point.
Example: Cumulative Student Marks
import matplotlib.pyplot as plt
marks = [
35, 40, 45, 50, 55,
60, 65, 70, 75, 80,
85, 90, 55, 65, 75,
45, 50, 60, 70, 80
]
plt.hist(
marks,
bins=5,
cumulative=True,
color="cornflowerblue",
edgecolor="black"
)
plt.title("Cumulative Histogram")
plt.xlabel("Marks")
plt.ylabel("Cumulative Frequency")
plt.show()
The cumulative=True parameter adds each bin's frequency to the total from the previous bins.
9. Comparing Multiple Histograms
You can compare two or more data distributions by plotting multiple histograms in the same chart. Transparency helps identify overlapping intervals.
Example: Comparing Marks of Two Classes
import matplotlib.pyplot as plt
class_a = [45, 50, 55, 60, 65, 70, 75, 80]
class_b = [50, 55, 60, 65, 70, 75, 80, 85]
plt.hist(
class_a,
bins=5,
alpha=0.6,
color="blue",
label="Class A"
)
plt.hist(
class_b,
bins=5,
alpha=0.6,
color="orange",
label="Class B"
)
plt.title("Comparison of Class Marks")
plt.xlabel("Marks")
plt.ylabel("Frequency")
plt.legend()
plt.show()
10. Adding Titles, Labels, and Grid Lines
Titles and labels explain the information displayed in a histogram. Grid lines make it easier to estimate frequencies.
| Function | Purpose |
|---|---|
| plt.title() | Adds a chart title. |
| plt.xlabel() | Adds the X-axis label. |
| plt.ylabel() | Adds the Y-axis label. |
| plt.grid() | Displays grid lines. |
| plt.legend() | Displays labels for data groups. |
Example: Formatted Histogram
import matplotlib.pyplot as plt
ages = [
18, 20, 22, 25, 27, 30,
32, 35, 37, 40, 42, 45,
25, 28, 30, 33, 36, 39
]
plt.hist(
ages,
bins=6,
color="purple",
edgecolor="black",
label="People"
)
plt.title("Age Distribution")
plt.xlabel("Age")
plt.ylabel("Frequency")
plt.grid(axis="y", linestyle="--", alpha=0.5)
plt.legend()
plt.show()
11. Histogram vs Bar Chart
Histograms and bar charts look similar, but they are used for different purposes. A histogram displays the distribution of numerical data, while a bar chart compares categories.
| Feature | Histogram | Bar Chart |
|---|---|---|
| Data Type | Continuous numerical data. | Categorical data. |
| Bars | Usually touch each other. | Usually have gaps. |
| Purpose | Shows data distribution. | Compares category values. |
| Matplotlib Function | plt.hist() | plt.bar() |
12. Saving a Histogram
You can save a histogram using the savefig() function. Matplotlib supports formats such as PNG, JPEG, SVG, and PDF.
Example: Saving a Histogram
import matplotlib.pyplot as plt
marks = [35, 40, 45, 50, 55, 60, 65, 70, 75, 80]
plt.hist(
marks,
bins=5,
color="skyblue",
edgecolor="black"
)
plt.title("Student Marks Histogram")
plt.savefig(
"student_histogram.png",
dpi=300,
bbox_inches="tight"
)
plt.show()
| Parameter | Description |
|---|---|
| student_histogram.png | Name and format of the saved histogram. |
| dpi=300 | Sets the output resolution. |
| bbox_inches="tight" | Adjusts the saved bounding box to fit the chart content. |
13. Common Mistakes While Creating Histograms
Beginners may face common problems while creating histograms. Understanding these issues helps you write correct Matplotlib code.
| Common Mistake | Solution |
|---|---|
| Using categorical text data in hist(). | Use numerical data to create a histogram. |
| Too many bins make the chart difficult to read. | Choose a suitable number of bins. |
| Too few bins hide important details. | Increase the number of bins when necessary. |
| Histogram bars are difficult to distinguish. | Use edgecolor to add borders. |
| Overlapping distributions are difficult to compare. | Use alpha to add transparency. |
| Chart is not displayed. | Call plt.show() in a normal Python script. |
14. Practical Activity
Task: Create an Employee Age Distribution Histogram
Create a histogram to understand the age distribution of employees in a company.
- Create a list containing employee ages.
- Use plt.hist() to create a histogram.
- Set the number of bins to 6.
- Set the bar colour to green.
- Add black borders to the bars.
- Add a chart title and axis labels.
- Enable grid lines.
- Save the chart as employee_age_distribution.png.
Starter Code
import matplotlib.pyplot as plt
employee_ages = [
22, 25, 28, 30, 32, 35,
38, 40, 42, 45, 27, 33,
36, 39, 41, 29, 31, 44
]
# Create your histogram here
plt.show()
15. Practice Questions
Test your understanding of Matplotlib histograms:
- What is a histogram?
- Which Matplotlib function creates a histogram?
- What is a bin in a histogram?
- What does the height of a histogram bar represent?
- Which parameter controls the number of bins?
- What is the purpose of the density parameter?
- What does cumulative=True do?
- How can you change the colour of histogram bars?
- What is the difference between a histogram and a bar chart?
- Which function is used to save a histogram?
Summary
In this lesson, you learned how to create histograms using Matplotlib. You explored the hist() function, bins, frequency, density, cumulative histograms, multiple distributions, and chart formatting.
- Use plt.hist() to create histograms.
- Use bins to divide numerical data into intervals.
- Use color to customize histogram bars.
- Use edgecolor to set bar borders.
- Use alpha to control transparency.
- Use density=True to create a normalized histogram.
- Use cumulative=True to display cumulative frequency.
- Use title(), xlabel(), and ylabel() to describe the chart.
- Use legend() to identify different data groups.
- Use savefig() to save the histogram.
You are now ready to create histograms and understand numerical data distributions using Matplotlib.