How to specify different colors for different bars in a Python matplotlib histogram?

To specify different colors for different bars in a matplotlib histogram, you can access the individual bar patches and modify their colors. This technique allows you to create visually distinct histograms with custom color schemes.

Basic Approach

The key is to capture the patches returned by hist() and iterate through them to set individual colors ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure size
plt.figure(figsize=(8, 5))

# Generate sample data
data = np.random.normal(50, 15, 1000)

# Create histogram and capture patches
n, bins, patches = plt.hist(data, bins=10, edgecolor='black', alpha=0.7)

# Define colors for each bar
colors = ['red', 'blue', 'green', 'orange', 'purple', 'brown', 'pink', 'gray', 'olive', 'cyan']

# Apply colors to each bar
for i, patch in enumerate(patches):
    patch.set_facecolor(colors[i % len(colors)])

plt.title('Histogram with Different Bar Colors')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.show()
A histogram with 10 bars, each colored differently using the specified color list.

Using Random Colors

You can generate random hex colors for a more dynamic appearance ?

import numpy as np
import matplotlib.pyplot as plt
import random

# Generate sample data
data = np.random.exponential(2, 500)

# Create histogram
n, bins, patches = plt.hist(data, bins=12, edgecolor='black', linewidth=1.2)

# Generate random colors for each bar
for patch in patches:
    # Generate random hex color
    color = "#{:06x}".format(random.randint(0, 0xFFFFFF))
    patch.set_facecolor(color)

plt.title('Histogram with Random Bar Colors')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.grid(True, alpha=0.3)
plt.show()
A histogram with 12 bars, each colored with a randomly generated hex color.

Color Based on Bar Height

You can also color bars based on their frequency values using a colormap ?

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.cm as cm

# Generate sample data
data = np.random.gamma(2, 2, 800)

# Create histogram
n, bins, patches = plt.hist(data, bins=15, edgecolor='black', alpha=0.8)

# Color bars based on their height using a colormap
colors = cm.viridis(n / max(n))  # Normalize heights to [0,1]

for patch, color in zip(patches, colors):
    patch.set_facecolor(color)

plt.title('Histogram Colored by Bar Height')
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.colorbar(cm.ScalarMappable(cmap=cm.viridis), label='Frequency')
plt.show()
A histogram with bars colored according to their heights using the viridis colormap, with a colorbar legend.

Key Points

  • The hist() function returns three values: counts, bin edges, and patches (the bar objects)

  • Use set_facecolor() to change individual bar colors

  • Colors can be specified as named colors, hex codes, or RGB tuples

  • Colormaps provide smooth color transitions based on data values

Conclusion

By accessing the patches returned by hist(), you can easily customize individual bar colors in matplotlib histograms. Use predefined color lists for consistent themes, random colors for variety, or colormaps for data-driven color schemes.

Updated on: 2026-03-26T19:01:18+05:30

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements