Back to Python
2026-03-245 min read

Matplotlib Histograms (Python Programming)

Learn Matplotlib Histograms (Python Programming) step by step with clear examples and exercises.

Title: Matplotlib Histograms (Python Programming)

Why This Matters

Histograms are a crucial graphical representation in data analysis, providing insights into the distribution of data sets. By learning how to create histograms using Matplotlib, we can effectively visualize patterns, trends, and outliers in our data, making it an essential skill for data scientists, analysts, and researchers.

Prerequisites

To fully grasp creating histograms with Matplotlib, you should have a strong understanding of the following:

  1. Python programming basics, including variables, functions, loops, and conditional statements.
  2. Numpy library for handling arrays, including basic array operations and creating arrays from various data sources.
  3. Familiarity with the Python standard library's random module for generating random numbers.
  4. Matplotlib library for plotting and visualizing data, including line plots, scatter plots, bar charts, and histograms.
  5. Basic understanding of how to install and import libraries in Python.

Core Concept

Creating a histogram using Matplotlib involves several steps: importing necessary libraries, creating an array containing our data, and using the hist() function to generate the histogram. Here's a step-by-step breakdown:

  1. Importing Libraries:
import numpy as np
import matplotlib.pyplot as plt
  1. Creating Data Array:
data = np.array([4, 7, 5, 6, 8, 9, 3, 1, 2, 5, 6, 7, 8, 9, 10])
  1. Generating Histogram:
plt.hist(data, bins=10)
plt.title('Histogram of Data Set')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.show()

In the code above, we first import the Numpy and Matplotlib libraries. Then, we create an array called data containing our data set. The hist() function generates the histogram with 10 bins (intervals) by default. We can adjust the number of bins using the bins parameter. Finally, we add a title, x-label, and y-label to the plot and display it using the show() method.

Customizing Histograms

Matplotlib allows us to customize various aspects of our histograms, such as the color, edge color, linewidth, and more. Here's an example of a customized histogram:

plt.hist(data, bins=10, alpha=0.5, edgecolor='black', linewidth=2)
plt.title('Customized Histogram of Data Set')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.show()

In this example, we've set the histogram's alpha value to 0.5 for transparency, edge color to black, and linewidth to 2 for a thicker border around each bar.

Histogram Properties

Histogram properties include:

  • bins: Number of intervals or bins in the histogram (default: 10).
  • range: The range of values that the histogram will cover (optional).
  • density: Whether to display a probability density histogram (set to True, default is False).
  • align: Alignment of the bars within each bin (can be 'left', 'mid', or 'right').
  • normed: Normalize the histogram so that the sum of the areas equals 1 (default is False).

Worked Example

Let's create a histogram for a larger data set containing 10,000 random numbers between 1 and 100:

import numpy as np
import matplotlib.pyplot as plt

Generate 10,000 random numbers between 1 and 100

data = np.random.randint(1, 101, size=10000)

Create histogram with 50 bins and customize it

plt.hist(data, bins=50, alpha=0.75, edgecolor='red', linewidth=2, density=True)

plt.title('Customized Density Histogram of Random Data Set (1-100)')

plt.xlabel('Values')

plt.ylabel('Probability Density')

plt.show()

Common Mistakes

  1. Forgetting to import Matplotlib: Make sure you import the Matplotlib library at the beginning of your script.
  2. Not defining data properly: Ensure that your data is defined as an array and contains valid numbers.
  3. Incorrect bin count: Adjust the number of bins according to your data set to avoid overlapping or empty bins.
  4. Missing plot labels: Always add a title, x-label, and y-label to your plots for clarity.
  5. Not displaying the plot: Call the show() method at the end of your script to visualize the generated histogram.
  6. Overlooking customization options: Explore Matplotlib's formatting functions to create visually appealing histograms.
  7. Neglecting to normalize probability density histograms: When creating a probability density histogram, set the density parameter to True.
  8. Failing to handle edge effects: To avoid edge effects in probability density histograms, use the pdf2hist() function instead of hist().

Practice Questions

  1. Create a histogram for the following data set using 20 bins and adjust the x-label to display 'Age': [18, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40]
  2. Generate a histogram for 500 random numbers between 50 and 150 with 25 bins and customize the appearance of the bars.
  3. Create a histogram for the following data set using 10 bins, adjust the x-label to display 'Grade', and customize the appearance of the bars: [75, 80, 85, 90, 95, 100]
  4. Generate a histogram for 1000 random numbers between -10 and 10 with 20 bins and save the resulting plot as an image file named 'histogram_example.png'.
  5. Create a probability density histogram for the following data set using 30 bins, adjust the x-label to display 'Speed (mph)', and normalize the histogram: [60, 62, 64, 66, 68, 70, 72, 74, 76, 78]
  6. Generate a probability density histogram for 1000 random numbers between 0 and 1 with 50 bins and save the resulting plot as an image file named 'pdf_example.png'.

FAQ

Q: How do I save the generated histogram as an image file?

A: You can use the savefig() function to save your plot as an image file in various formats like PNG, JPEG, or SVG. For example:

plt.savefig('histogram_example.png')

Q: How do I customize the appearance of my histogram (colors, line styles, etc.)?

A: You can customize various aspects of your plot using Matplotlib's formatting functions like plot(), bar(), and more. For example, to change the color of the bars in a histogram:

plt.hist(data, bins=10, color='blue')

Q: How do I add a legend to my histogram?

A: You can add a legend to your plot using the legend() function. For example:

plt.hist(data, bins=10, color='blue', alpha=0.75)
plt.title('Customized Histogram of Data Set')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.legend(['Histogram'])
plt.show()

Q: How do I create a probability density histogram?

A: To create a probability density histogram, set the density parameter to True when calling the hist() function or use the pdf2hist() function instead.

Q: What is the difference between a histogram and a probability density histogram?

A: A histogram displays the frequency of data points within specified bins, while a probability density histogram shows the estimated probability distribution function (PDF) of the data by normalizing the histogram so that the sum of the areas equals 1.

Matplotlib Histograms (Python Programming) | Python | XQA Learn