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

I have a long list of words, and I want to create a histogram of the frequency of each word in my list. I was able to do this in the code below:

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()

However, it does not display cells by rank (i.e., by frequency, so the highest frequency is the first bit on the left, etc.), although when printing, countshe orders them for me Counter({'C': 4, 'A': 3, 'B': 2}), How can I achieve this?

+4
source share
1 answer

, , bar; numpy.argsort. ( ):

enter image description here

, :

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.

, .

+8

All Articles