使用Pyplot进行光滑表面绘图

时间:2016-02-02 15:38:26

标签: python numpy matplotlib

我的问题几乎与此相似: smoothing surface plot from matrix

只是我的工具集是matplotlib和numpy(到目前为止)。

我成功地生成了一个X,Y和Z网格来绘制 与

fig = plt.figure(figsize=(12,12))
ax = fig.add_subplot(111, projection='3d')
ax.plot_surface(X, Y, Z, cmap='summer', rstride=1, cstride=1, alpa=None)

然而,由于价值观非常惊人,因此看起来非常糟糕。 Exampleplot - terribly edgy, ugly... not usable and stuff

我想使事情平滑,至少使顶点连接起来,或者看起来像那样。

我的数据生成如下: 我有一个功能

svOfMatrix(x, y)

产生依赖于x的矩阵,计算其y次幂,选择列和行的子集,并计算最大奇异值。 所以,Z [x,y]是svOfMatrix(x,y)

由于这个计算非常昂贵,我不想让x的步骤太小,Y必然是整数 此外,即使是非常小的步骤,也可能会有一些变化,我不想看到。所以我想以某种方式插入它。 我发现 http://docs.scipy.org/doc/scipy-0.14.0/reference/tutorial/interpolate.html 但是我没有让它发挥作用。

1 个答案:

答案 0 :(得分:8)

从您建议的链接中,示例here可能与您想要的最接近。您可以将示例与您的值一起使用,

import numpy as np
from scipy import interpolate
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import axes3d, Axes3D

X, Y = np.mgrid[-1:1:20j, -1:1:20j]
Z = (X+Y) * np.exp(-6.0*(X*X+Y*Y)) + np.random.rand(X.shape[0])

xnew, ynew = np.mgrid[-1:1:80j, -1:1:80j]
tck = interpolate.bisplrep(X, Y, Z, s=0)
znew = interpolate.bisplev(xnew[:,0], ynew[0,:], tck)

fig = plt.figure(figsize=(12,12))
ax = fig.gca(projection='3d')
ax.plot_surface(X, Y, Z, cmap='summer', rstride=1, cstride=1, alpha=None)
plt.show()

fig = plt.figure(figsize=(12,12))
ax = fig.gca(projection='3d')
ax.plot_surface(xnew, ynew, znew, cmap='summer', rstride=1, cstride=1, alpha=None, antialiased=True)
plt.show()

此外,antialiased=True可能会让它看起来更好,但我认为默认情况下会启用。第一个情节看起来像这样,

enter image description here

和这样的平滑情节,

enter image description here

数据中的低频噪声问题在于很难定义足够精确的网格来解决。您可以使用s参数interpolate.bisplrep调整平滑级别,也可以粗粒度/过滤数据,只留下主要趋势(例如,如果您有常规网格化数据,请使用scipy.ndimage.interpolation.zoom)。或者,考虑一种不同类型的绘图,例如pcolormesh,因为数据本质上是2D。