Histogram for discrete values with Matplotlib

To plot a histogram for discrete values with Matplotlib, we can use the hist() method. Discrete histograms are useful for visualizing the frequency distribution of categorical or integer data points.

Steps

  • Set the figure size and adjust the padding between and around the subplots.

  • Create a list of discrete values.

  • Use hist() method to plot data with bins=length of data and edgecolor='black'.

  • To display the figure, use show() method.

Example

Let's create a histogram for discrete values with proper bin configuration ?

import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

data = [1, 4, 2, 3, 5, 9, 6, 7]
plt.hist(data, bins=len(data), edgecolor='black')
plt.title('Histogram for Discrete Values')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.show()

Better Approach for Discrete Data

For truly discrete data, it's often better to use specific bin edges to ensure each value gets its own bin ?

import matplotlib.pyplot as plt
import numpy as np

# Sample discrete data with repeated values
scores = [1, 2, 2, 3, 3, 3, 4, 4, 5, 6, 6, 7]

# Create bins centered on each discrete value
unique_values = sorted(set(scores))
bin_edges = np.arange(min(unique_values) - 0.5, max(unique_values) + 1.5, 1)

plt.figure(figsize=(8, 4))
plt.hist(scores, bins=bin_edges, edgecolor='black', alpha=0.7, color='skyblue')
plt.title('Histogram of Discrete Scores')
plt.xlabel('Score')
plt.ylabel('Frequency')
plt.xticks(unique_values)
plt.grid(axis='y', alpha=0.3)
plt.show()

Key Parameters for Discrete Histograms

Parameter Purpose Example Value
bins Number of bins or bin edges len(data) or custom edges
edgecolor Color of bin borders 'black'
alpha Transparency level 0.7
color Fill color of bins 'skyblue'

Conclusion

Use plt.hist() with appropriate bin configuration for discrete data. For better visualization, set custom bin edges using np.arange() to center bins on discrete values and add labels for clarity.

Updated on: 2026-03-25T21:12:13+05:30

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements