matplotlib如何将轴值显示为字符串而不是浮点范围

时间:2017-05-06 23:25:31

标签: python matplotlib

我编写了以下脚本来绘制python列表中项目的频率。当列表是字符串时,我无法在x轴上显示实际的字符串值,我收到此错误:

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

1 个答案:

答案 0 :(得分: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