0

I want to make a bargraph or piechart to see how many times each item in a list is represented. Some dummy data...

mylist = [a,a,b,c,c,c,c,d,d]

What I want is a bar chart that'd reflect (a = 2, b = 1, c = 4 etc...)

In reality, I have a much longer list and it is not something to do manually. I started to make a "for loop" that'd compare each item with the previous, and create a new list if different than the last, but even that seems cumbersome. There has to be a simple and elegant way to do this. I am sorry if this has already been addressed, when searching I either get results too simple or overly complicated. This got tagged as a duplicate for how to count elements in a list, this is different because it also addresses the graphing.

joe5
  • 1,101
  • 2
  • 8
  • 10
  • Possible duplicate of [How to count the occurrences of a list item?](https://stackoverflow.com/questions/2600191/how-to-count-the-occurrences-of-a-list-item) –  Aug 20 '18 at 21:55

3 Answers3

2

What you can do is just to iterate over the list and update the dictionary with the frequency of each item.
Example:

import matplotlib.pyplot as plt

mylist = ['a','a','b','c','c','c','c','d','d']

#create a dictionary with the frequency of each item
frequencies = {}
for item in mylist:
    if item in frequencies:
        frequencies[item]+=1
    else:
        frequencies[item] = 1

# plot it
plt.figure()
plt.bar(frequencies.keys(), frequencies.values())
plt.show()
abc
  • 11,579
  • 2
  • 26
  • 51
1

Try using this:

from collections import Counter
mylist = [a,a,b,c,c,c,c,d,d]
Counter(mylist)
  • 1
    This works too. Thanks for showing me this, I wasn't aware of Counter but it seems to be the way to go. – joe5 Aug 21 '18 at 01:47
0

Just another solution:

import collections
import matplotlib.pyplot as plt
figure = plt.figure(figsize=(8,6))

mylist = ['a','a','b','c','c','c','c','d','d']
co = collections.Counter(mylist)
plt.bar(range(len(co.keys())), list(co.values()), tick_label=list(co.keys()))
plt.xlabel('Items')
plt.ylabel('Frequency'), list(co.values()), tick_label=list(co.keys()))

Output

enter image description here

Sheldore
  • 37,862
  • 7
  • 57
  • 71