How do I use colorbar with hist2d in matplotlib.pyplot?

To use colorbar with hist2d() in matplotlib, you need to capture the return value from hist2d() and pass the mappable object to colorbar(). The histogram returns a tuple containing the mappable object needed for the colorbar.

Basic hist2d with Colorbar

Here's how to create a 2D histogram with a colorbar ?

import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
N = 1000
x = np.random.rand(N)
y = np.random.rand(N)

# Create 2D histogram
fig, ax = plt.subplots(figsize=(8, 6))
h = ax.hist2d(x, y, bins=30)

# Add colorbar using the mappable object (h[3])
fig.colorbar(h[3], ax=ax)

ax.set_xlabel('X values')
ax.set_ylabel('Y values')
ax.set_title('2D Histogram with Colorbar')
plt.show()

Understanding hist2d Return Values

The hist2d() function returns a tuple with four elements ?

import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
x = np.random.normal(0, 1, 1000)
y = np.random.normal(0, 1, 1000)

fig, ax = plt.subplots(figsize=(8, 6))
h = ax.hist2d(x, y, bins=25)

# h[0]: counts (2D array)
# h[1]: x bin edges  
# h[2]: y bin edges
# h[3]: mappable object for colorbar

print(f"Counts shape: {h[0].shape}")
print(f"X bin edges: {len(h[1])}")
print(f"Y bin edges: {len(h[2])}")
print(f"Mappable type: {type(h[3])}")

# Use the mappable object for colorbar
fig.colorbar(h[3], ax=ax, label='Count')
plt.show()
Counts shape: (25, 25)
X bin edges: 26
Y bin edges: 26
Mappable type: <class 'matplotlib.collections.QuadMesh'>

Using Different Normalizations

You can apply logarithmic scaling for better visualization of data with wide value ranges ?

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import LogNorm

# Generate clustered data
N = 2000
x = np.concatenate([np.random.normal(2, 0.5, N//2), 
                    np.random.normal(6, 0.8, N//2)])
y = np.concatenate([np.random.normal(3, 0.6, N//2), 
                    np.random.normal(7, 0.7, N//2)])

fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(12, 5))

# Regular histogram
h1 = ax1.hist2d(x, y, bins=30)
fig.colorbar(h1[3], ax=ax1)
ax1.set_title('Linear Scale')

# Logarithmic histogram
h2 = ax2.hist2d(x, y, bins=30, norm=LogNorm())
fig.colorbar(h2[3], ax=ax2)
ax2.set_title('Logarithmic Scale')

plt.tight_layout()
plt.show()

Customizing the Colorbar

You can customize the colorbar appearance and add labels ?

import matplotlib.pyplot as plt
import numpy as np

# Generate sample data
x = np.random.exponential(2, 1500)
y = np.random.exponential(1.5, 1500)

fig, ax = plt.subplots(figsize=(10, 7))

# Create histogram with custom colormap
h = ax.hist2d(x, y, bins=40, cmap='plasma')

# Customize colorbar
cbar = fig.colorbar(h[3], ax=ax, shrink=0.8, aspect=20)
cbar.set_label('Frequency', rotation=270, labelpad=20)

ax.set_xlabel('X values')
ax.set_ylabel('Y values') 
ax.set_title('2D Histogram with Custom Colorbar')

plt.show()

Key Points

Element Description Usage
h[0] 2D counts array Access histogram values
h[1] X bin edges Get bin boundaries
h[2] Y bin edges Get bin boundaries
h[3] Mappable object Required for colorbar

Conclusion

To add a colorbar to hist2d(), capture the return tuple and use the mappable object (h[3]) with fig.colorbar(). You can customize the colorbar with different normalizations and styling options for better data visualization.

Updated on: 2026-03-26T14:59:27+05:30

907 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements