python怎么做直方图,在python中绘制Matplotlib直方图

I faced an error when I tried to plot histogram in python.

Could you please help me to solve this error?

I think it is not a big issue, but I can find the solution yet. :(

Code

import matplotlib.pyplot as plt

import csv

import sys

def analyze():

# datafile = 'test.csv'

datafile = sys.argv[1]

pieces = []

with open(datafile, 'rt') as f:

data = csv.reader(f,delimiter = '\t')

for d in data:

pieces.append(d)

x = [op for op, response, interval in pieces]

y1 = [interval for op, response, interval in pieces]

plt.figure()

plt.hist(y1)

plt.show()

if __name__ == '__main__':

analyze()

Error Message :

File "./scripts/plot_histo.py", line 27, in

analyze()

File "./scripts/plot_histo.py", line 23, in analyze

plt.hist(y1)

File "/usr/local/anaconda2/lib/python2.7/site-packages/matplotlib/pyplot.py", line 2958, in hist

stacked=stacked, data=data, **kwargs)

File "/usr/local/anaconda2/lib/python2.7/site-packages/matplotlib/__init__.py", line 1812, in inner

return func(ax, *args, **kwargs)

File "/usr/local/anaconda2/lib/python2.7/site-packages/matplotlib/axes/_axes.py", line 5995, in hist

if len(xi) > 0:

TypeError: len() of unsized object

Data file format :

653070 232.93 104981.00

653071 277.94 104981.00

653072 232.93 12695.00

653073 232.93 25878.00

653074 232.93 32714.00

653075 232.93 19532.00

653076 232.93 19532.00

653077 232.93 32715.00

653078 232.93 32715.00

653079 232.93 45899.00

653080 232.93 65430.00

653081 232.93 65430.00

Continued .......

..........

解决方案

Try to debug your code. You will find y1 is a list of strings, so plt.hist(y1) will raise

TypeError: len() of unsized object

TypeError raised when an operation or function is applied to an object of

inappropriate type.

That means you should use float or int, so try to run this:

y1 = [float(interval) for op, response, interval in pieces]

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值