user17978261
user17978261

Reputation:

How to make bar plot of a list in Python

I have a list that has counts of some values and I want to make a bar plot to see the counts as bars. The list is like:

print(lii)
# Output
[46, 11, 9, 20, 3, 15, 8, 63, 11, 9, 24, 3, 5, 45, 51, 2, 23, 9, 17, 1, 1, 37, 29, 6, 3, 9, 25, 5, 43]

I want something like this plot with each list value as a bar and its value on top:

bar

I tried the following code but it plotted the list as a series:

plt.figure(figsize=(30, 10))
plt.plot(lii)
plt.show()

plot

Any help is appreciated.

Upvotes: 1

Views: 10803

Answers (2)

hajben
hajben

Reputation: 321

I believe you want something like this:

ax = sns.barplot(x=np.arange(len(lii)), y=lii)
ax.bar_label(ax.containers[0])
plt.axis('off')
plt.show()

Bar plot

Upvotes: 5

seb007
seb007

Reputation: 568

You can do it using matplotlib pyplot bar.

This example considers that lii is the list of values to be counted.

If you already have the list of unique values and associated counts, you do not have to compute lii_unique and counts.

import matplotlib.pyplot as plt

lii = [46, 11, 9, 20, 3, 15, 8, 63, 11, 9, 24, 3, 5, 45, 51, 2, 23, 9, 17, 1, 1, 37, 29, 6, 3, 9, 25, 5, 43]

# This is a list of unique values appearing in the input list
lii_unique = list(set(lii))

# This is the corresponding count for each value
counts = [lii.count(value) for value in lii_unique]

barcontainer = plt.bar(range(len(lii_unique)),counts)

# Some labels and formatting to look more like the example
plt.bar_label(barcontainer,lii_unique, label_type='edge')
plt.axis('off')
plt.show()

Here is the output. The label above each bar is the value itself, while the length of the bar is the count for this value. For example, value 9 has the highest bar because it appears 4 times in the list.

enter image description here

Upvotes: 3

Related Questions