我不是科学家,所以请假设我不知道有经验的程序员的行话,或者科学绘图技术的复杂性. Python是我所知道的唯一语言(初学者,也许是中级).
任务:将多元回归的结果(z = f(x,y))绘制为3D图形上的二维平面(例如,我可以使用OSX的图形工具,或者在此使用R实现Plot Regression Surface).
经过一周搜索Stackoverflow并阅读matplotlib,seaborn和mayavi的各种文档后,我终于找到了Simplest way to plot 3d surface given 3d points,听起来很有希望.所以这是我的数据和代码:
首先尝试使用matplotlib:
shape: (80,3)
type:
我得到的是一个空的3D坐标框架,其中包含以下错误消息:
RuntimeError:qhull Delaunay三角测量计算中的错误:奇异输入数据(exitcode = 2);使用python verbose选项(-v)来查看原始的qhull错误.
我试着看看我是否可以使用绘图参数并检查这个网站http://www.qhull.org/html/qh-impre.htm#delaunay,但我真的无法理解我应该做什么.
第二次尝试使用mayavi:
相同的数据,分为3个numpy数组:
type:
码:
from mayavi import mlab
def multiple3_triple(tpl_lst):
X = xs
Y = ys
Z = zs
# Define the points in 3D space
# including color code based on Z coordinate.
pts = mlab.points3d(X,Y,Z,Z)
# Triangulate based on X,Y with Delaunay 2D algorithm.
# Save resulting triangulation.
mesh = mlab.pipeline.delaunay2d(pts)
# Remove the point representation from the plot
pts.remove()
# Draw a surface based on the triangulation
surf = mlab.pipeline.surface(mesh)
# Simple plot.
mlab.xlabel("x")
mlab.ylabel("y")
mlab.zlabel("z")
mlab.show()
我得到的就是:
如果这很重要,我在OSX 10.9.3上使用64位版本的Enthought’s Canopy
对于我做错了什么的输入,将不胜感激.
编辑:发布有效的最终代码,以防有人帮助.
'''After the usual imports'''
def multiple3(tpl_lst):
mul = []
for tpl in tpl_lst:
calc = (.0001*tpl[0]) + (.017*tpl[1])+ 6.166
mul.append(calc)
return mul
fig = plt.figure()
ax = fig.gca(projection='3d')
'''some skipped code for the scatterplot'''
X = np.arange(0,40000,500)
Y = np.arange(0,40,.5)
X,Y = np.meshgrid(X,Y)
Z = multiple3(zip(X,Y))
surf = ax.plot_surface(X,rstride=1,cstride=1,cmap=cm.autumn,linewidth=0,antialiased=False,alpha =.1)
ax.set_zlim(1.01,11.01)
ax.set_xlabel(' x = IPP')
ax.set_ylabel('y = UNRP20')
ax.set_zlabel('z = DI')
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf,shrink=0.5,aspect=5)
plt.show()
最佳答案
对于matplotlib,你可以基于surface example(你缺少plt.meshgrid):
from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator,FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np
fig = plt.figure()
ax = fig.gca(projection='3d')
X = np.arange(-5,5,0.25)
Y = np.arange(-5,0.25)
X,Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)
surf = ax.plot_surface(X,cmap=cm.coolwarm,antialiased=False)
ax.set_zlim(-1.01,1.01)
ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
fig.colorbar(surf,aspect=5)
plt.show()