2017-05-06 21 views
1

我寫了下面的腳本來繪製一個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() 
+0

請注意'matplotlib.pyploy.bar()'只接受標量作爲參數的序列。 ** [檢查參考](https://matplotlib.org/api/pyplot_api.html?highlight=bar#matplotlib.pyplot.bar)** –

回答

2

您首先需要限定軸線作爲整數

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

,然後將它們映射到實際str對象

plt.xticks(range(0, len(votes_count)), [row[0] for row in votes_count]) 

最後,3個最後重構行:

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() 

輸出: enter image description here

+0

我試過了,得到的列不是按照正確的順序(a,c ,b,d)有沒有辦法解決這個問題? –

+0

@A_Matar您可以更改訂單,更改'votes'列表。順序將是如何在您的列表中出現字母的順序 –

相關問題