Matplotlib histogram with multiple legend entries

Creating a histogram with multiple legend entries in Matplotlib allows you to categorize data visually with colored bars and corresponding legend labels. This is useful for highlighting different data ranges or categories within your distribution.

Basic Histogram with Multiple Legend Entries

Here's how to create a histogram where different bars are colored according to categories ?

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle

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

# Generate sample data
data = np.random.rayleigh(size=1000) * 35

# Create histogram
N, bins, patches = plt.hist(data, 30, ec="k")

# Define colors for different categories
colors = ["red", "yellow", "green"]

# Color each bar according to the pattern
for i in range(0, len(bins)-1):
    patches[i].set_facecolor(colors[i % len(colors)])

# Create legend handles and labels
handles = [Rectangle((0, 0), 1, 1, color=c, ec="k") for c in colors]
labels = ["Red", "Yellow", "Green"]
plt.legend(handles, labels)

plt.title("Histogram with Multiple Legend Entries")
plt.xlabel("Values")
plt.ylabel("Frequency")
plt.show()

Alternative Method Using Data Categories

You can also create legends based on actual data categories rather than just visual grouping ?

import matplotlib.pyplot as plt
import numpy as np

# Create categorized data
np.random.seed(42)
low_values = np.random.normal(10, 2, 300)
medium_values = np.random.normal(20, 3, 400)
high_values = np.random.normal(30, 2, 300)

# Plot multiple histograms
plt.figure(figsize=(8, 5))
plt.hist(low_values, bins=20, alpha=0.7, label='Low Range', color='blue', edgecolor='black')
plt.hist(medium_values, bins=20, alpha=0.7, label='Medium Range', color='orange', edgecolor='black')
plt.hist(high_values, bins=20, alpha=0.7, label='High Range', color='red', edgecolor='black')

plt.title("Histogram with Categorical Data")
plt.xlabel("Values")
plt.ylabel("Frequency")
plt.legend()
plt.show()

Customizing Legend Position and Style

You can control legend appearance and positioning for better visualization ?

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.patches import Rectangle

# Generate data
data = np.random.exponential(scale=2, size=1000) * 10

# Create histogram
plt.figure(figsize=(9, 5))
N, bins, patches = plt.hist(data, 25, ec="black", linewidth=0.5)

# Define colors and corresponding ranges
colors = ["lightcoral", "gold", "lightgreen", "lightblue"]
ranges = ["0-10", "10-20", "20-30", "30+"]

# Color bars based on value ranges
for i, patch in enumerate(patches):
    if bins[i] < 10:
        patch.set_facecolor(colors[0])
    elif bins[i] < 20:
        patch.set_facecolor(colors[1])
    elif bins[i] < 30:
        patch.set_facecolor(colors[2])
    else:
        patch.set_facecolor(colors[3])

# Create custom legend
handles = [Rectangle((0, 0), 1, 1, color=colors[i], ec="black") for i in range(4)]
plt.legend(handles, ranges, loc='upper right', title="Value Ranges", frameon=True, fancybox=True, shadow=True)

plt.title("Customized Histogram Legend")
plt.xlabel("Values")
plt.ylabel("Frequency")
plt.grid(True, alpha=0.3)
plt.show()

Key Components

Component Purpose Usage
plt.hist() Creates histogram Returns N, bins, patches
patches[i].set_facecolor() Sets bar colors Individual bar coloring
Rectangle() Creates legend handles Custom legend entries
plt.legend() Displays legend Links handles with labels

Conclusion

Multiple legend entries in histograms help categorize and explain different data groups or value ranges. Use Rectangle() patches for custom legend handles and set_facecolor() to color individual bars according to your categorization scheme.

Updated on: 2026-03-25T21:36:14+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements