【问题标题】:3D Surface Plot where z is a function that takes a vector formed from x and y3D 曲面图,其中 z 是一个函数,它采用由 x 和 y 形成的向量
【发布时间】:2018-05-13 05:33:14
【问题描述】:

我正在尝试生成一个 3D 曲面图,其中 X 和 Y 的值介于 -50 和 50 之间,并且 Z 由取决于 X 和 Y 的函数计算。

该函数以np数组形式的向量作为参数。向量的第一行是来自 X 的值,第二行是来自 Y 的值。X 和 Y 的所有组合都应该产生 Z 值,因此是网格网格。

这是我的实现,对于 Z,我目前正在创建一个向量,其中第一行是 X 的整个数据集,第二行是 Y 的整个数据集。这当然是不正确的。

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import matplotlib.pyplot as plt

def myFunction(v):
    return v.dot(np.array([1, 2]))

fig = plt.figure()
ax = fig.gca(projection='3d')

# Make data.
X = np.linspace(-50,50, 100)
Y = np.linspace(-50,50, 100)
X, Y = np.meshgrid(X, Y)
Z = myFunction(np.array([X, Y])) # <-- Here is the problem

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.Greens,
                       linewidth=0, antialiased=False)


ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

我希望我有道理, 谢谢

【问题讨论】:

  • 您显示的代码是正确的。这完全取决于myFunction 是什么。但是,如果您遗漏了唯一有问题的部分,您在这里期待什么?
  • 例如,如果myFunction = lambda c: np.exp(-c[0,:,:]**2/230.-c[1,:,:]**2/330.),则情节看起来像like this
  • 您好,感谢您的回复。我添加了 myFunction 的简化版本,但它基本上执行相同的操作,我目前收到以下错误:“ValueError:形状(2,100,100)和(2,)未对齐:100(dim 2)!= 2(dim 0 )"
  • 输入数组是 3D,而 [1, 2] 是 1D。如何定义 3D 和 1D 数组的点积?
  • 我认为这可能是我解释得不好/完全有错误想法的地方,我希望 x 和 y 的每个组合产生相应的 z 值,而不是在整个数据集 X 上调用 myFunction以及整个数据集 Y。

标签: python matplotlib vector 3d


【解决方案1】:

您可能希望向函数提供一个数组,其中包含第一列中的所有 x 值和第二列中的所有 y 值。这将确保尺寸与点积相匹配。然后可以将结果重新调整为网格的形状。

Z = myFunction(np.array([X.flatten(), Y.flatten()]).T).reshape(X.shape)

完整示例:

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import numpy as np
import matplotlib.pyplot as plt

def myFunction(v):
    return v.dot(np.array([1, 2]))

fig = plt.figure()
ax = fig.gca(projection='3d')

# Make data.
X = np.linspace(-50,50, 100)
Y = np.linspace(-50,50, 100)
X, Y = np.meshgrid(X, Y)
Z = myFunction(np.array([X.flatten(), Y.flatten()]).T).reshape(X.shape)

# Plot the surface.
surf = ax.plot_surface(X, Y, Z, cmap=cm.Greens,
                       linewidth=0, antialiased=False)


ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)

plt.show()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-10-21
    • 2016-09-07
    • 2011-11-02
    • 2018-04-22
    • 2019-04-11
    • 2013-02-26
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多