我正在使用matplotlib绘制两个参数的函数。我在matplotlib教程中复制了一个例子并用我自己的输入数据进行了转换:向量X和Y(在-3:3中等间隔数字)和Z =峰值(X,Y),峰值是我定义为befohand的函数。有什么问题?
def peaks(x,y):
xsq=x**2
ysq=y**2
xsq_one=(x+1)**2
ysq_one=(y+1)**2
m1=3*(1-x)**2
m2=10*(x/5-x**3-y**5)
m3=1/3
return m1*numpy.exp(-xsq-ysq_one)-m2*numpy.exp(-xsq-ysq)-m3*numpy.exp(-xsq_one-ysq)
from mpl_toolkits.mplot3d import axes3d
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
X=Y=numpy.arange(-3,3,0.01).tolist()
Z=[]
for i in range(len(X)):
Z.append(peaks(X[i],Y[i]))
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contour(X, Y, Z, zdir='z', offset=-100)
cset = ax.contour(X, Y, Z, zdir='x', offset=-40)
cset = ax.contour(X, Y, Z, zdir='y', offset=40)
ax.set_xlabel('X')
ax.set_xlim(-40, 40)
ax.set_ylabel('Y')
ax.set_ylim(-40, 40)
ax.set_zlabel('Z')
ax.set_zlim(-100, 100)
plt.show()
感谢您的建议!
答案 0 :(得分:6)
您需要生成meshgrid。 X,Y和Z必须是2D数组
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
def peaks(x,y):
return x * numpy.sin(y)
fig = plt.figure()
ax = fig.gca(projection='3d')
X = Y= numpy.arange(-3, 3, 0.1).tolist()
X, Y = numpy.meshgrid(X, Y)
Z = []
for i in range(len(X)):
Z.append(peaks(X[i],Y[i]))
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contour(X, Y, Z, zdir='z', offset=-8)
cset = ax.contour(X, Y, Z, zdir='x', offset=-8)
cset = ax.contour(X, Y, Z, zdir='y', offset=8)
ax.set_xlabel('X')
ax.set_xlim(-8, 8)
ax.set_ylabel('Y')
ax.set_ylim(-8, 8)
ax.set_zlabel('Z')
ax.set_zlim(-8, 8)
plt.show()
答案 1 :(得分:1)
接受的答案不再适用。可悲的是,审稿人拒绝了我的建议编辑,这将使其成为一个工作asnwer。所以这里再次给出相同的答案,但需要做一些小改动才能使它在matplotlib的当前版本中运行。
import numpy
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d
def peaks(x,y):
return x * numpy.sin(y)
fig = plt.figure()
ax = fig.gca(projection='3d')
X = Y= numpy.arange(-3, 3, 0.1).tolist()
X, Y = numpy.meshgrid(X, Y)
Z = numpy.zeros(X.shape)
for i in range(len(X)):
for j in range(len(Y)):
Z[i,j] = peaks(X[i,j],Y[i,j])
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
cset = ax.contour(X, Y, Z, zdir='z', offset=-8)
cset = ax.contour(X, Y, Z, zdir='x', offset=-8)
cset = ax.contour(X, Y, Z, zdir='y', offset=8)
ax.set_xlabel('X')
ax.set_xlim(-8, 8)
ax.set_ylabel('Y')
ax.set_ylim(-8, 8)
ax.set_zlabel('Z')
ax.set_zlim(-8, 8)
plt.show()