1

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.

3
  • 2
    use plt.bar() instead of plt.plot() matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar.html Commented Mar 2, 2022 at 13:25
  • TypeError: bar() missing 1 required positional argument: 'height' Commented Mar 2, 2022 at 13:32
  • 2
    did you look at the documentation of bar and provide an array for the x axis and an array for y axis right? Using bar instead of plot doesn;t mean replacing literally plot for bar, it means reading what bar does and adapting your code to use this new function Commented Mar 2, 2022 at 13:32

2 Answers 2

5

I believe you want something like this:

import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np

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

Bar plot

Sign up to request clarification or add additional context in comments.

Comments

3

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

3 Comments

Don't you think the first item of list (46) should have the highest bar and then others?
Anyways, thanks for the answer :)
I was not sure what was the lii list. Since your question provides a single list rather than a list of values + a list of counts, I assumed (wrongly?) that lii was 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 but the answer remains valid.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.