Matplotlib griddata失败

时间:2015-03-31 16:45:56

标签: python numpy matplotlib

我正在尝试编写一个函数,该函数根据格式为“x,y,z”的文本数据文件(或numpy数组)生成等高线图。但是,当我尝试使用griddata插入数据时,出现“类型”错误:

    if not len(x)==len(y)==len(z):
TypeError: object of type 'numpy.float64' has no len()

这是我的功能:

def ContourPlot(datafile,columns=[0,1,2], nXvals=100, nYvals=100, title='', xlab='', ylab='', colormap='rainbow', contours=10):

        if type(datafile)==type(str()):
                try:
                        x, y, z = np.loadtxt(datafile, dtype='float', unpack=True, usecols=columns)
                except:
                        print "Can't open the input file!"
                        exit
        elif type(datafile)==np.ndarray:
                        x = datafile[0]
                        y = datafile[1]
                        z = datafile[2]
        else:
                        print "ERROR: You tried to pass data to the ContourPlot() function in a format it cannot read"
                        exit

        print type(x)

        xi = np.linspace(np.amin(x), np.amax(x), nXvals)
        yi = np.linspace(np.amin(y), np.amax(y), nYvals)
        zi = griddata(x, y, z, xi, yi)
        norm = colors.Normalize(vmin = np.min(z), vmax = np.max(z), clip = False)
        pl.figure()
        pl.contourf(xi, yi, zi, 30, cmap = pl.get_cmap(colormap), norm =norm)
        CS = pl.contour(xi, yi, zi, colors = 'k',lw = 3, levels= contours)
        pl.clabel(CS, inline=1, fontsize=10)
        pl.tick_params(axis='x', labelsize=20)
        pl.tick_params(axis='y', labelsize=20)
        pl.title(title, fontsize=17)
        pl.xlabel(xlab, fontsize=20)
        pl.ylabel(ylab, fontsize=20)
        pl.show()

我尝试使用tolist()方法将x,y,z转换为常规Python列表,但它不起作用。

非常感谢任何帮助!

1 个答案:

答案 0 :(得分:0)

我想您使用的是较旧版本的matplotlib?你从哪里导入griddata?查看matplotlib / mlab.py文件中的griddate函数,看看是否有类似于

的行
if not len(x)==len(y)==len(z):
    raise TypeError("inputs x,y,z must all be 1D arrays of the same length")

https://github.com/matplotlib/matplotlib/blob/master/lib/matplotlib/mlab.py的当前版本不再有此行,但现在以这种方式检查:

# Check input arguments.
x = np.asanyarray(x, dtype=np.float64)
y = np.asanyarray(y, dtype=np.float64)
z = np.asanyarray(z, dtype=np.float64)
if x.shape != y.shape or x.shape != z.shape or x.ndim != 1:
    raise ValueError("x, y and z must be equal-length 1-D arrays")

因此,对更新版本的更新可能已经解决了您的问题。在任何情况下,当前至少有一个x,y,z输入的类型为numpy.float64,并且由于某种原因没有len()。