等高线图,TypeError:y的长度必须是z中的行数 [英] Contour plot, TypeError: Length of y must be number of rows in z

查看:686
本文介绍了等高线图,TypeError:y的长度必须是z中的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了一个带有两个参数func(x,y)的函数.我现在想将其绘制为2D等高线图,首先是func(x,y) vs. x,然后是func(x,y) vs. y.

I have created a function with two arguments, func(x,y). I would now like to plot this as a 2D contour plot, first as func(x,y) vs. x, and then func(x,y) vs. y.

我将x值的numpy数组设置为从5e48e4的20个值,并将y值设置为从1e101e12的20个值.然后,我的函数func(x,y)将这两个数组用作参数.

I set my numpy array for x-values as 20 values from 5e4 to 8e4, and the y-values as 20 values from 1e10 to 1e12. My function func(x,y) then takes these two arrays as arguments.

因此,我将情节设置如下:

So, I set up my plot as follows:

import matplotlib
import matplotlib.pyplot as plt 
import numpy as np
import matplotlib.cm as cm
import matplotlib.mlab as mlab

matplotlib.rcParams['xtick.direction'] = 'out'
matplotlib.rcParams['ytick.direction'] = 'out'

x = np.logspace( 5e4, 8e4, num=20) 
y = np.logspace(1e10, 1e12, num=20)
z = np.asarray([ func(x, y), x ])
plt.figure()
CS = plt.contour(x, y, z)
plt.clabel(CS, inline=1, fontsize=10)

我的numpy数组的形状是:

The shapes for my numpy arrays are:

print x.shape
print y.shape
print z.shape

输出

(20,)
(20,)
(2, 20)

我的错误是

TypeError: Length of y must be number of rows in z.

为什么会这样?尺寸看起来正确.

Why would that be? The dimensions look correct.

推荐答案

来自 contour 的文档:" X和Y 都必须是与Z形状相同的二维图形,或者它们都必须是一维图形,使得len( X)是Z中的列数,len(Y)是Z中的行数.(这是一维X和Y的版本.

From the docs for contour: "X and Y must both be 2-D with the same shape as Z, or they must both be 1-D such that len(X) is the number of columns in Z and len(Y) is the number of rows in Z." (This is the version for 1D X and Y.)

您的基本问题是Z必须是矩形,因此您的情况可能是20x20.也就是说,可以将等高线图视为在图像之类的位置上放置水平线.

Your basic problem here is that Z needs to be rectangular, so probably 20x20 in your case. That is, think of a contour plot as putting levels on something like an image.

据我所知,这是一个符合您需要的工作版本:

As best I can figure it out, here's a working version that's along the lines of what you want:

import pylab as pb    
import numpy as np
import matplotlib.pyplot as plt

def f(x, y):
    return np.log(x**2 + y**2)

x = np.logspace( np.log10(5e4), np.log10(8e4), num=20) 
y = np.logspace(np.log10(5e4), np.log10(9e4), num=20)
X, Y = np.meshgrid(x, y)

z = f(X, Y)
print x
print y
print min(z.flat), max(z.flat), min(x), max(x), min(y), max(y)

plt.figure()
CS = plt.contour(x, y, z)
plt.clabel(CS, inline=1, fontsize=10)

pb.show()

我认为您未使用 meshgrid (尽管也有其他方法可以做到这一点).

I think the key that you're not using meshgrid (although there are other means of getting this too).

这篇关于等高线图,TypeError:y的长度必须是z中的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆