如何使用matplotlib绘制柱条?

问题描述 投票:0回答:1

我有一个示例数据文件包含以下数据

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']

如何解决错误并绘制列图?

matplotlib
1个回答
0
投票

根据我有限的经验,它看起来你正在读取所有数据作为字符串而不是数字类型。我用过的一个简单的解决方法是使用astype函数来更改数据类型。每当我加载数据时,我也使用numpy的loadtext函数 - 您不需要创建文件对象,并且可以快速指定您正在寻找的数据类型和分隔符。

© www.soinside.com 2019 - 2024. All rights reserved.