HimanAB
HimanAB

Reputation: 2573

Plot histogram of a list of strings in Python

I have a very long list of IDs (IDs are string values. I want to plot a histogram of this list. There are some codes in other threads on stackoverflow for plotting a histogram but the histogram I want should look like this picture (i.e. highest values are in the left side and the values gradually decrease when x-axis increase.

This is the code for plotting regular histogram

import pandas
from collections import Counter
items=a long list of strings
letter_counts = Counter(items)
df = pandas.DataFrame.from_dict(letter_counts, orient='index')
df.plot(kind='bar')

The histogram

Upvotes: 2

Views: 5265

Answers (1)

Aaron
Aaron

Reputation: 11075

how about something along these lines...

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

counts = Counter(['a','a','a','c','a','a','c','b','b','d', 'd','d','d','d','b'])
common = counts.most_common()
labels = [item[0] for item in common]
number = [item[1] for item in common]
nbars = len(common)

plt.bar(np.arange(nbars), number, tick_label=labels)
plt.show()

The most_common() call is the main innovation of this script. The rest is easily found in the matplotlib documentation (already linked in my comment).

Upvotes: 1

Related Questions