How to plot collections.Counter histogram using Matplotlib?

To plot a histogram with collections.Counter, we can use the bar() method from Matplotlib. The Counter object automatically counts the frequency of each element, making it perfect for creating histograms from raw data.

Basic Counter Histogram

Here's how to create a simple histogram using Counter ?

import collections
from matplotlib import pyplot as plt

# Sample data
data = [0, 1, 2, 4, 1, 3, 0, 4, 1, 4, 3, 5, 6, 5, 2]

# Count frequencies using Counter
counter = collections.Counter(data)
print("Counter object:", counter)

# Create bar plot
plt.figure(figsize=(8, 5))
plt.bar(counter.keys(), counter.values())
plt.xlabel('Values')
plt.ylabel('Frequency')
plt.title('Histogram using collections.Counter')
plt.show()
Counter object: Counter({1: 3, 4: 3, 0: 2, 3: 2, 5: 2, 2: 2, 6: 1})

Customizing the Histogram

You can enhance the histogram with colors, grid, and sorted keys ?

import collections
from matplotlib import pyplot as plt

# Sample text data
text = "hello world hello python world programming"
words = text.split()

# Count word frequencies
word_counter = collections.Counter(words)

# Sort by keys for better visualization
sorted_items = sorted(word_counter.items())
keys, values = zip(*sorted_items)

# Create customized bar plot
plt.figure(figsize=(10, 6))
bars = plt.bar(keys, values, color=['skyblue', 'lightcoral', 'lightgreen', 'gold'])
plt.xlabel('Words')
plt.ylabel('Frequency')
plt.title('Word Frequency Histogram')
plt.xticks(rotation=45)
plt.grid(axis='y', alpha=0.3)

# Add value labels on bars
for bar, value in zip(bars, values):
    plt.text(bar.get_x() + bar.get_width()/2, bar.get_height() + 0.05, 
             str(value), ha='center', va='bottom')

plt.tight_layout()
plt.show()

Counter vs Regular Histogram

Method Best For Advantage
Counter + bar() Categorical data Automatic counting, exact values
plt.hist() Continuous data Binning, density plots

Conclusion

Use collections.Counter with plt.bar() to create histograms from categorical or discrete data. Counter automatically handles frequency counting, making it ideal for text analysis and categorical data visualization.

Updated on: 2026-03-25T23:20:24+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements