在python中绘制Matplotlib直方图 [英] Ploting Matplotlib Histogram in python
本文介绍了在python中绘制Matplotlib直方图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试在python中绘制直方图时遇到错误. 您能帮我解决这个错误吗? 我认为这不是一个大问题,但是我可以找到解决方案. :(
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. :(
代码
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()
错误消息:
File "./scripts/plot_histo.py", line 27, in <module>
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
数据文件格式:
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 .......
..........
推荐答案
尝试调试代码.您会发现y1
是字符串列表,因此plt.hist(y1)
会引发
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 类型不正确.
TypeError raised when an operation or function is applied to an object of inappropriate type.
这意味着您应该使用float
或int
,因此请尝试运行此代码:
That means you should use float
or int
, so try to run this:
y1 = [float(interval) for op, response, interval in pieces]
这篇关于在python中绘制Matplotlib直方图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文