Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
What are n, bins and patches in matplotlib?
The hist() method in matplotlib returns three important values: n, bins, and patches. Understanding these return values helps you customize and analyze histogram plots effectively.
Understanding the Return Values
n represents the values (heights) of the histogram bins − essentially the frequency count for each bin. bins defines the bin edges, which determine how the data is grouped into intervals. patches are the visual containers (rectangles) that make up the histogram bars, allowing you to modify their appearance.
Basic Example
Let's create a histogram and examine what each return value contains ?
import numpy as np
import matplotlib.pyplot as plt
# Generate sample data
x = np.random.normal(0, 1, 1000)
# Create histogram and capture return values
n, bins, patches = plt.hist(x, bins=10)
print("n (frequencies):", n)
print("bins (edges):", bins)
print("Number of patches:", len(patches))
plt.title("Basic Histogram")
plt.show()
Customizing Histogram Appearance
You can modify individual bars using the patches object ?
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.random.normal(size=100)
n, bins, patches = plt.hist(x, bins=20)
# Color the highest bar differently
max_height = max(n)
for i, patch in enumerate(patches):
if n[i] == max_height:
patch.set_facecolor('red')
else:
patch.set_facecolor('lightblue')
plt.title("Histogram with Custom Colors")
plt.show()
Analyzing Histogram Data
Use the return values to extract statistical information ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
data = np.random.exponential(2, 1000)
n, bins, patches = plt.hist(data, bins=30, alpha=0.7)
# Find the bin with maximum frequency
max_freq_index = np.argmax(n)
max_freq_bin_center = (bins[max_freq_index] + bins[max_freq_index + 1]) / 2
print(f"Maximum frequency: {n[max_freq_index]}")
print(f"Bin with max frequency: {max_freq_bin_center:.2f}")
# Highlight the maximum frequency bin
patches[max_freq_index].set_facecolor('orange')
plt.title("Exponential Distribution Histogram")
plt.xlabel("Value")
plt.ylabel("Frequency")
plt.show()
Summary
| Return Value | Type | Description |
|---|---|---|
n |
Array | Frequency counts for each bin |
bins |
Array | Bin edges (length = n + 1) |
patches |
List | Rectangle objects for visual customization |
Conclusion
The hist() method returns n for frequency data, bins for interval boundaries, and patches for visual customization. These values enable both statistical analysis and visual enhancement of your histograms.
