numpy 多元函数的等高线作图

qv7cva1a  于 2022-11-10  发布在  其他
关注(0)|答案(1)|浏览(128)

我有一个多元函数

X是(2,1),A(100,2),b是(100,1)。
我怎么用Python语言绘制它的等高线呢?对于Z=X^2+Y^2这样的简单情况,我有这个代码,但我认为它不能解决我的问题。

x, y = np.linspace(-3, 3, 400), np.linspace(-3, 3, 400)

XX, YY = np.meshgrid(x, y)

Z = (XX**2 + YY**2)

fig, ax = plt.subplots()

ax.contour(XX, YY, Z)

如何绘制函数的等高线?

bpzcxfmw

bpzcxfmw1#

我假设在图中的公式中,xX相同,X表示2D平面中一个点的坐标。
然后,使用np.meshgrid创建通常的坐标网格,在该网格上计算函数xxyy。此时,您需要将它们组合成一个2行(表示x和y坐标)和任意多个列的矩阵X
最后,对X的每一列计算函数。

import numpy as np
import matplotlib.pyplot as plt

# create example data

x = y = np.linspace(0, 2 * np.pi, 100)
A = np.stack([np.cos(x), np.sin(x * y)]).T
b = np.cbrt(x * y)
print("A.shape = ", A.shape)
print("b.shape = ", b.shape)

# define the function

f = lambda X: np.linalg.norm(b - A @ X, 2)**2

# creates the coordinates over which the function

# will be evaluated

x = y = np.linspace(-np.pi, np.pi, 200)
xx, yy = np.meshgrid(x, y)

# assemble the coordinates into a "vector of coordinates"

X = np.stack([xx, yy]).reshape(2, -1)
print("X.shape = ", X.shape)

# apply the function f on each pair of coordinates

Z = np.apply_along_axis(f, 0, X).reshape(xx.shape)
print("Z.shape = ", Z.shape)

fig, ax = plt.subplots()
c = ax.contourf(xx, yy, Z)
fig.colorbar(c)
plt.show()

相关问题