jjn*_*jjn 5 python plot distribution frequency matplotlib
我想制作一个单词频率分布,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)]
Run Code Online (Sandbox Code Playgroud)
我试着先把它转换成一个pandas DataFrame,然后使用pd.hist()下面的例子中的as,但我只是想不出来,并认为它实际上是直接的,但可能我错过了一些东西.
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()
Run Code Online (Sandbox Code Playgroud)
使用熊猫:
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')
Run Code Online (Sandbox Code Playgroud)
您不能将words matplotlib.pyplot.bar直接传递给。但是,您可以为其创建一个索引数组bar,然后words使用using 替换这些索引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()
Run Code Online (Sandbox Code Playgroud)
该for-loop创建word并frequency还可以通过简单的更换zipUND名单拆包:
word, frequency = zip(*example_list)
Run Code Online (Sandbox Code Playgroud)