最常见的单词列表 输出如下:
[('film',904),('movie',561),('one',379),('like',292)]
我希望根据数字
使用matplotlib为每个单词生成一个图表请帮帮我
答案 0 :(得分:3)
以下是使用条形图快速采用此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()
答案 1 :(得分:1)
你可以试试这个:
"""
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