Python 绘制循环中生成函数的轮廓图
我想为一个函数 z
画一个轮廓图(它的值在 zlist
里),坐标轴上显示的是参数 x
和 y
。这个 z
是在两个循环里生成的,我在里面指定了不同的 x
和 y
。但是当我运行这个代码时,出现了一个错误 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
根据chthonicdaemon的建议,
X,Y = np.meshgrid(xlist,ylist)
_, Z = myfunction(X,Y)
plt.figure()
plt.contour(X,Y,Z)
plt.show()