Reputation: 2320
I wrote the following script to plot the frequencies of items in a python list. When the list is of strings, I am not able to display the actual string values on the x axis and I get this error:
Traceback (most recent call last):
File "testy.py", line 15, in <module>
plt.bar([row[0] for row in votes_count], [row[1] for row in votes_count])
File "...\matplotlib\pyplot.py", line 2705, in bar
**kwargs)
File "....\matplotlib\__init__.py", line 1891, in inner
return func(ax, *args, **kwargs)
File "....\matplotlib\axes\_axes.py", line 2105, in bar
left = [left[i] - width[i] / 2. for i in xrange(len(left))]
TypeError: unsupported operand type(s) for -: 'str' and 'float'
Here is the code:
from collections import Counter
import matplotlib.pyplot as plt
import plotly.plotly as py #pip install plotly
votes = ['a','a','b','c','d']
tmp_votes_count = Counter (votes)
votes_count = []
for i in tmp_votes_count:
votes_count.append ([i, tmp_votes_count[i]])
margin = 2
most_common_vote= [item for item in Counter(votes).most_common(1)]
plt.bar([row[0] for row in votes_count], [row[1] for row in votes_count])
plt.axis([0,4,0,most_common_vote[0][1]+margin])
plt.show()
Upvotes: 1
Views: 801
Reputation: 23484
You firstly need to define axis as integers
plt.bar(range(0, len(votes_count)), [row[1] for row in votes_count])
and then map them to actual str
objects
plt.xticks(range(0, len(votes_count)), [row[0] for row in votes_count])
Finally, 3 last refactored lines:
plt.bar(range(0, len(votes_count)), [row[1] for row in votes_count])
plt.xticks(range(0, len(votes_count)), [row[0] for row in votes_count])
plt.show()
Upvotes: 2