grouping items in a list for a barchart in matplot lib and python
grouping items in a list for a barchart in matplot lib and python
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.
3 Answers
3
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()
This is exactly what I was looking for! Thanks @newbie
– joe5
Aug 21 at 1:46
Try using this:
from collections import Counter
mylist = [a,a,b,c,c,c,c,d,d]
Counter(mylist)
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 at 1:47
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
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Possible duplicate of How to count the occurrences of a list item?
– PlikePotato
Aug 20 at 21:55