【问题标题】:plot the most common words given by counters in python [closed]绘制python中计数器给出的最常见单词[关闭]
【发布时间】:2016-08-06 14:29:00
【问题描述】:

最常用词列表 输出如下:

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

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

请帮帮我

【问题讨论】:

  • 到目前为止你有什么代码?
  • 实际上我尝试以不同的方式使用 matplotlib。但是我找到了 x=[a, b, c] 和 y = [1, 3,4] 之类的输入解决方案,或者其他类似表格的解决方案。但我没有得到上述输出的解决方案。
  • 我做对了吗:如果您有两个列表并且现在正在寻找一种方法从您的数据中创建两个列表,您知道该怎么做吗?
  • 只要x, y = map(list, zip(*L)),你就可以像以前一样继续。

标签: python python-3.x matplotlib graph counter


【解决方案1】:

这是使用条形图快速采用此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()

【讨论】:

  • namesvalues可以用zip生产:names, values = zip(*data)
  • 没想到,谢谢提醒!确实更甜。
  • 谢谢,效果很好!!!
  • 调用zip()*的目的是什么
【解决方案2】:

你可以试试这个:

"""
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

【讨论】:

  • 是的,它也在工作......感谢您的建议......
猜你喜欢
  • 1970-01-01
  • 2020-12-30
  • 1970-01-01
  • 2018-06-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多