使用元组元素从列表中生成频率直方图

问题描述 投票:5回答:2

我想制作一个单词频率分布,x轴上的字和y轴上的频率计数。

我有以下列表:

example_list = [('dhr', 17838), ('mw', 13675), ('wel', 5499), ('goed', 5080), 
                ('contact', 4506), ('medicatie', 3797), ('uur', 3792),
                ('gaan', 3473), ('kwam', 3463), ('kamer', 3447), 
                ('mee', 3278), ('gesprek', 2978)] 

我试图先把它转换成一个pandas DataFrame,然后使用pd.hist(),如下例所示,但我无法弄明白并认为它实际上是直接的,但可能我错过了一些东西。

import numpy as np
import matplotlib.pyplot as plt

word = []
frequency = []

for i in range(len(example_list)):
  word.append(example_list[i][0])
  frequency.append(example_list[i][1])


plt.bar(word, frequency, color='r')
plt.show()
python matplotlib plot distribution frequency
2个回答
4
投票

你无法直接将words传递给matplotlib.pyplot.bar。但是,您可以为bar创建一个索引数组,然后使用words将这些索引替换为matplotlib.pyplot.xticks

import numpy as np
import matplotlib.pyplot as plt

indices = np.arange(len(example_list))
plt.bar(indices, frequency, color='r')
plt.xticks(indices, word, rotation='vertical')
plt.tight_layout()
plt.show()

enter image description here

用于创建forwordfrequency循环也可以用简单的zip和列表解包来代替:

word, frequency = zip(*example_list)

5
投票

使用熊猫:

import pandas as pd
import matplotlib.pyplot as plt

example_list = [('dhr', 17838), ('mw', 13675), ('wel', 5499), ('goed', 5080), ('contact', 4506), ('medicatie', 3797), ('uur', 3792), ('gaan', 3473), ('kwam', 3463), ('kamer', 3447), ('mee', 3278), ('gesprek', 2978)] 

df = pd.DataFrame(example_list, columns=['word', 'frequency'])
df.plot(kind='bar', x='word')

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.