Matplotlib 3D 绘图 - 输入数据的 2D 格式? [英] Matplotlib 3D plot - 2D format for input data?

查看:44
本文介绍了Matplotlib 3D 绘图 - 输入数据的 2D 格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在用 matplotlib 绘制两个参数的函数.我在 matplotlib 教程中复制了一个示例,并使用我自己的输入数据进行了转换:向量 X 和 Y(在 -3:3 中的数字相等)和 Z=peaks(X,Y) 带有我事先定义的函数的峰值.怎么了?

I am plotting a function of two parameters with matplotlib. I copied an example in matplotlib tutorial and transformed with my own input data: vectors X and Y (equally spaces numbers in -3:3) and Z=peaks(X,Y) with peaks a function that I defined befohand. What is wrong?

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()

感谢您的建议!

推荐答案

您需要生成网格.X、Y 和 Z 必须是二维数组

You need to generate the meshgrid. X,Y and Z must be 2D arrays

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]))

# Z must be an array
Z = numpy.array(Z)

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()

这篇关于Matplotlib 3D 绘图 - 输入数据的 2D 格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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