Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to plot collections.Counter histogram using matplotlib?

How to plot histogram of following Counter object?:

w = collections.Counter()
l = ['a', 'b', 'b', 'b', 'c']
for o in l:
    w[o]+=1
like image 976
Leopoldo Avatar asked Sep 29 '18 20:09

Leopoldo


People also ask

How do I display the count over the bar in MatPlotLib histogram?

To display the count over the bar in matplotlib histogram, we can iterate each patch and use text() method to place the values over the patches.

How do I show multiple histograms in MatPlotLib?

Set the figure size and adjust the padding between and around the subplots. Make two dataframes, df1 and df2, of two-dimensional, size-mutable, potentially heterogeneous tabular data. Create a figure and a set of subplots.


2 Answers

Looking at your data and attempt, I guess you want a bar plot instead of a histogram. Histogram is used to plot a distribution but that is not what you have. You can simply use the keys and values as the arguments of plt.bar. This way, the keys will be automatically taken as the x-axis tick-labels.

import collections
import matplotlib.pyplot as plt
l = ['a', 'b', 'b', 'b', 'c']
w = collections.Counter(l)
plt.bar(w.keys(), w.values())

enter image description here

like image 173
Sheldore Avatar answered Oct 12 '22 18:10

Sheldore


I'm guessing this is what you want to do? You'd just have to add xtick labels(see matplotlib documentation)

import matplotlib.pyplot as plt
import collections

l = ['a', 'b', 'b', 'b', 'c']

count = collections.Counter(l)
print(count)

plt.bar(range(len(count)), count.values())
plt.show()
like image 32
SV-97 Avatar answered Oct 12 '22 20:10

SV-97