Histogram
What You'll Learn: In this tutorial, you'll discover how to use Matplotlib's hist() function to create histograms. A histogram is a graph showing frequency distributions, which represents the number of observations within each given interval.
What is a Histogram?
A histogram is a type of graph that shows how frequently different values occur within a dataset. For example, if you ask for the height of 250 people, a histogram could show you how many people fall within certain height ranges.
Example: Height Distribution
Let's consider the height of 250 people. A histogram might look like this:
- 2 people from 140 to 145 cm
- 5 people from 145 to 150 cm
- 15 people from 151 to 156 cm
- 31 people from 157 to 162 cm
- 46 people from 163 to 168 cm
- 53 people from 168 to 173 cm
- 45 people from 173 to 178 cm
- 28 people from 179 to 184 cm
- 21 people from 185 to 190 cm
- 4 people from 190 to 195 cm
Create a Histogram
In Matplotlib, you can use the hist() function to create histograms. This function takes an array of numbers and creates a histogram based on that data.
Example: Generate random data and create a histogram
import numpy as np
import matplotlib.pyplot as plt
# Generate an array with 250 values, centered around 170 with a standard deviation of 10
x = np.random.normal(170, 10, 250)
# Create the histogram
plt.hist(x)
plt.show()
Result:
This will generate a histogram based on the randomly generated data, showing the frequency distribution of the heights.
Try It Yourself: Fun Exercises
- Generate Different Data:
- Try generating different datasets with varying means and standard deviations, and create histograms for each.
- Customize the Histogram:
- Experiment with different bin sizes and colors to customize the appearance of the histogram.
Summary:
In this tutorial, we learned how to create histograms using Matplotlib in Python. We explored the concept of histograms, generated random data, and created a histogram to show the frequency distribution. Keep experimenting and have fun with Matplotlib in Python!