如何生成词频直方图,其中条形根据高度排序

How to generate a word frequency histogram, where bars are ordered according to their height

我有一长串单词,我想生成列表中每个单词出现频率的直方图。我能够在下面的代码中做到这一点:

import csv
from collections import Counter
import numpy as np

word_list = ['A','A','B','B','A','C','C','C','C']

counts = Counter(merged)

labels, values = zip(*counts.items())

indexes = np.arange(len(labels))

plt.bar(indexes, values)
plt.show()

但是,它不会按等级显示 bin(即按频率,因此最高频率是左侧的第一个 bin,依此类推),即使我打印 counts 它会为它们排序我 Counter({'C': 4, 'A': 3, 'B': 2})。我怎样才能做到这一点?

您可以先对数据进行排序,然后将排序后的数组传递给 bar,从而获得所需的输出;下面我为此使用 numpy.argsort 。然后情节如下所示(我还在栏中添加了标签):

这是生成带有一些内联注释的图的代码:

from collections import Counter
import numpy as np
import matplotlib.pyplot as plt

word_list = ['A', 'A', 'B', 'B', 'A', 'C', 'C', 'C', 'C']

counts = Counter(word_list)

labels, values = zip(*counts.items())

# sort your values in descending order
indSort = np.argsort(values)[::-1]

# rearrange your data
labels = np.array(labels)[indSort]
values = np.array(values)[indSort]

indexes = np.arange(len(labels))

bar_width = 0.35

plt.bar(indexes, values)

# add labels
plt.xticks(indexes + bar_width, labels)
plt.show()

如果你只想绘制前 n 个条目,你可以替换行

counts = Counter(word_list)

来自

counts = dict(Counter(word_list).most_common(n))

在上述情况下,counts 将是

{'A': 3, 'C': 4}

对于 n = 2

如果你喜欢去掉图框直接标注条形,可以勾选this post