绘制 python 中计数器给出的最常用词

plot the most common words given by counters in python

最常用词列表 输出如下:

[('film', 904), ('movie', 561), ('one', 379), ('like', 292) ]

我想要一个根据数字使用 matplotlib 为每个单词绘制的图表

请帮帮我

你可以试试这个:

"""
Bar chart demo with pairs of bars grouped for easy comparison.
"""
import numpy as np
import matplotlib.pyplot as plt

data = [('film', 904), ('movie', 561), ('one', 379), ('like', 292)]

n_groups = len(data)

vals_films = [x[1] for x in data]
legends_films = [x[0] for x in data]

fig, ax = plt.subplots()

index = np.arange(n_groups)
bar_width = 0.25

opacity = 0.4

rects1 = plt.bar(index, vals_films, bar_width,
                 alpha=opacity,
                 color='b',
                 label='Ocurrences')


plt.xlabel('Occurrences')
plt.ylabel('Words')
plt.title('Occurrences by word')
plt.xticks(index + bar_width, legends_films)
plt.legend()

plt.tight_layout()
plt.show()

如果您恰好使用 Jupyter Notebook(强烈推荐),请将此添加到笔记本的开头:%matplotlib notebook

这是使用条形图快速采用此 example 的方法。

#!/usr/bin/env python
# a bar plot with errorbars
import numpy as np
import matplotlib.pyplot as plt


data = [('film', 904), ('movie', 561), ('one', 379), ('like', 292)]
names, values = zip(*data)  # @comment by Matthias
# names = [x[0] for x in data]  # These two lines are equivalent to the the zip-command.
# values = [x[1] for x in data] # These two lines are equivalent to the the zip-command.

ind = np.arange(len(data))  # the x locations for the groups
width = 0.35       # the width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(ind, values, width, color='r')

# add some text for labels, title and axes ticks
ax.set_ylabel('Count')
ax.set_xticks(ind+width/2.)
ax.set_xticklabels(names)



def autolabel(rects):
    # attach some text labels
    for rect in rects:
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., 1.05*height,
                '%d' % int(height),
                ha='center', va='bottom')

autolabel(rects1)

plt.show()