我寫了下面的腳本來繪製一個python列表中的項目的頻率。當列表是一個字符串,我不能夠在X軸顯示的實際字符串值,我得到這個錯誤:matplotlib如何顯示軸值作爲字符串不是一個浮動範圍
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'
下面是代碼:
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()
請注意'matplotlib.pyploy.bar()'只接受標量作爲參數的序列。 ** [檢查參考](https://matplotlib.org/api/pyplot_api.html?highlight=bar#matplotlib.pyplot.bar)** –