如何使用matplotlib绘制列栏?

时间:2018-11-25 17:51:50

标签: matplotlib

我有一个样本数据文件,其中包含以下数据

Item,%Frequency
 1,15.08
 2,11.80
 3,10.52
 4,9.00
 5,6.74
 6,4.94
 7,5.84
 8,6.34
 9,6.42
 10,5.24
 11,3.64
 12,2.10
 13,1.46
 14,0.50
 15,0.06
 16,0.06

我正在尝试使用以下脚本使用matplotlib绘制列栏。

import matplotlib.pyplot as plt
import numpy as np
lines = []
with open("sample.txt") as fname:
    lines = fname.readlines()
    size = len(lines)

i = 1
x = []
y = []
while i<size:
    ip = lines[i].split(',')
    x.append(ip[0])
    y.append(ip[1])
    i+=1
plt.bar(x, y)
plt.savefig("output.png")
plt.close()

我收到以下错误消息。

$ python plot_v1.py 



File "plot_v1.py", line 22, in <module>
    plt.bar(x, y)
  File "/usr/lib/python2.7/dist-packages/matplotlib/pyplot.py", line 2573, in bar
    ret = ax.bar(left, height, width=width, bottom=bottom, **kwargs)
  File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_axes.py", line 2046, in bar
    self.add_patch(r)
  File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 1550, in add_patch
    self._update_patch_limits(p)
  File "/usr/lib/python2.7/dist-packages/matplotlib/axes/_base.py", line 1570, in _update_patch_limits
    xys = patch.get_patch_transform().transform(vertices)
  File "/usr/lib/python2.7/dist-packages/matplotlib/patches.py", line 626, in get_patch_transform
    self._update_patch_transform()
  File "/usr/lib/python2.7/dist-packages/matplotlib/patches.py", line 619, in _update_patch_transform
    bbox = transforms.Bbox.from_bounds(x, y, width, height)
  File "/usr/lib/python2.7/dist-packages/matplotlib/transforms.py", line 829, in from_bounds
    return Bbox.from_extents(x0, y0, x0 + width, y0 + height)
TypeError: cannot concatenate 'str' and 'float' objects

当我尝试打印列表x时,会得到以下结果

[' 1', ' 2', ' 3', ' 4', ' 5', ' 6', ' 7', ' 8', ' 9', ' 10', ' 11', ' 12', ' 13', ' 14', ' 15', ' 16']

如何解决错误并绘制柱形图?

1 个答案:

答案 0 :(得分:0)

根据我的有限经验,您似乎正在以字符串而不是数字类型读取所有数据。我使用的一种简单修复方法是使用astype函数来更改数据类型。每当加载数据时,我也会使用numpy的loadtext函数-您不需要创建文件对象,并且可以快速指定要查找的数据类型和定界符。