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

2024-05-15 13:00:18 发布

您现在位置:Python中文网/ 问答频道 /正文

我想做一个单词的频率分布,单词在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数据帧,然后使用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()

Tags: importexampleascontactplt单词listword
2条回答

使用熊猫:

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

不能将word直接传递到^{}中。但是,您可以为bar创建索引数组,然后使用^{}将这些索引替换为words

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

创建wordfrequencyfor-循环也可以替换为简单的zip和列表解包:

word, frequency = zip(*example_list)

相关问题 更多 >