在python中绘制Matplotlib直方图

时间:2017-01-17 07:20:22

标签: python matplotlib histogram

当我尝试在python中绘制直方图时遇到错误。 你能帮我解决一下这个错误吗? 我认为这不是一个大问题,但我可以找到解决方案。 :(

代码

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 .......
 ..........

1 个答案:

答案 0 :(得分:0)

尝试调试代码。您会发现a <- fit2$coefficients # fitted quadratic polynomial coefficients f <- function(x) { as.numeric(a[1] + a[2]*x + a[3]*x^2-4) } df <- function(x) { as.numeric(a[2] + 2*a[3]*x) } Newton.Raphson <- function(x0) { eps <- 1e-6 x <- x0 while(TRUE) { x <- x0 - f(x0) / df(x0) if (abs(x - x0) < eps) { return(x0) } x0 <- x } } t1 <- Sys.time() x1 <- Newton.Raphson(-10) x2 <- Newton.Raphson(10) x1 #[1] -6.453783 x2 #[1] -1.853398 s2 print(paste('time taken to compute the roots:' ,Sys.time() - t1)) #[1] "time taken to compute the roots: 0.0160109996795654" points(x1, 4, pch=19, col='green') points(x2, 4, pch=19, col='green') abline(v=x1, col='green') abline(v=x2, col='green') 是一个字符串列表,因此y1将会提升

plt.hist(y1)
  

将操作或函数应用于对象时引发的TypeError   不合适的类型。

这意味着您应该使用TypeError: len() of unsized object float,因此请尝试运行此操作:

int