Python绘制for循环中生成的函数轮廓

时间:2014-08-24 22:23:35

标签: python matplotlib contour

我想为函数z(其值在zlist)中绘制轮廓图,其中轴显示参数xyz在两个for循环中生成,我指定了不同的xy。我运行时遇到错误TypeError: Input z must be a 2D array。我如何操纵zlist以便它可以绘制?

import numpy as np
import matplotlib.pyplot as plt

def myfunction(x,y):
    c = x + 2*y
    z = c*x + 0.5*y
    return c,z

xlist = np.linspace(0,1,10)
ylist = np.linspace(0,10,20)

X,Y = np.meshgrid(xlist,ylist)

zlist = []

for x in xlist:

    for y in ylist:

        z = myfunction(x,y)[1]
        zlist.append(z)

plt.figure()        
plt.contour(X,Y,zlist)

plt.show()

1 个答案:

答案 0 :(得分:0)

遵循chthonicdaemon的建议,

X,Y = np.meshgrid(xlist,ylist)

_, Z = myfunction(X,Y)

plt.figure()        
plt.contour(X,Y,Z)

plt.show()