简体   繁体   English

在matplot lib和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] 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...) 我想要的是可以反映的条形图(a = 2,b = 1,c = 4等)

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. 我开始制作一个“ for循环”,将每个项目与上一个进行比较,如果与上一个不同,则创建一个新列表,但这看起来很麻烦。 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. 这被标记为重复的方式,用于计数列表中的元素,这是不同的,因为它也处理了图形。

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()

Try using this: 尝试使用此:

from collections import Counter
mylist = [a,a,b,c,c,c,c,d,d]
Counter(mylist)

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 产量

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM