A_Matar
A_Matar

Reputation: 2330

plot how many times each list entry is repeated using pyplot

I have list containing votes (smth like this votes = [1, 2, 3, 4, 1, 1, 3, 4, 4, 4]). How to use pyplot to plot a graph showing the count of each vote (i.e. 1 -> 3 votes, 2 -> 1 vote, 3 -> 2 votes, 4 -> 4 votes)

Here is how I am doing it:

from collections import Counter
import matplotlib.pyplot as plt

votes = [1,1,1,2,3,3,4,4,4,4,4]
tmp_votes_count = Counter (votes)
votes_count = []

for i in tmp_votes_count:
    votes_count.append ([i, tmp_votes_count[i]])

plt.plot([row[0] for row in votes_count], [row[1] for row in votes_count])
plt.axis([0,4,0,20])
plt.show()

Is there a more optimized way to do it? Also how to style the graph as bar chart instead of the continuous line? I mean smth similar to this:

enter image description here

instead of what I am getting right now: enter image description here

Upvotes: 0

Views: 414

Answers (2)

BENY
BENY

Reputation: 323376

If you know pandas , it will be very easy.

votes=pd.DataFrame(data=votes,columns=['List'])
votes.List.hist()

Upvotes: 1

vishes_shell
vishes_shell

Reputation: 23554

Just do

plt.bar([row[0] for row in votes_count], [row[1] for row in votes_count])

Upvotes: 1

Related Questions