2

我必须为 function 绘制轮廓图和线框图公式。这是我到目前为止的代码:

# Number of uniformly ditributed random numbers
n = 2000

def func_vec(x1s, x2s):
    return x1s * x1s + 4 * x2s * x2s

np.random.seed()
x1s = np.random.uniform(-1, 1, n)
x2s = np.random.uniform(-1, 1, n)
ys = func_vec(x1s, x2s)

fig = plt.figure()

# Scatter
ax1 = fig.add_subplot(1, 2, 1)
ax1.scatter(x1s, x2s, color = 'g', s = 2, edgecolor = 'none')
ax1.set_ylim([-1,1])
ax1.set_xlim([-1,1])

# Contour
ax1.contour(x2s, x1s, ys[np.newaxis,:].repeat(n, axis = 0))

# 3D visualization
ax2 = fig.add_subplot(1, 2, 2, projection = '3d')
X = x1s
Y = x2s
Z = ys
ax2.plot_wireframe(X, Y, Z, rstride = 1, cstride = 1)

plt.show()

我不明白的是如何做contour()plot_firewrame()实际工作?有人可以这么好心并向我解释一下(在指定功能的情况下)吗?此外,我应该如何指定 X、Y 和 Z?

这是情节现在的样子: 在此处输入图像描述

这就是它的样子(上面的散布可以正常工作): 在此处输入图像描述

4

1 回答 1

3

这是生成正确绘图的代码。任何为此苦苦挣扎的人都应该发现代码几乎不言自明:

# Number of uniformly ditributed random numbers
n = 2000

def func_vec(x1s, x2s):
    return x1s * x1s + 4 * x2s * x2s

np.random.seed()
x1s = np.random.uniform(-1, 1, n)
x2s = np.random.uniform(-1, 1, n)
ys = func_vec(x1s, x2s)

fig = plt.figure(22)

# Scatter
ax1 = fig.add_subplot(1, 2, 1)
ax1.scatter(x1s, x2s, color = 'g', s = 2, edgecolor = 'none')
ax1.set_ylim([-1,1])
ax1.set_xlim([-1,1])

# Contour
xi = np.linspace(-1,1,20)
yi = np.linspace(-1,1,20)
zi = griddata((x2s, x1s), ys, (xi[None,:], yi[:,None]), method = 'cubic')
ax1.contour(xi, yi, zi, 6, linewidths = 1, colors = ('#0000ff', '#0099ff', '#009999', '#999900', '#ff9900', '#ff0000'))

# 3D visualization
ax2 = fig.add_subplot(1, 2, 2, projection = '3d')
X, Y = np.meshgrid(xi, yi)
ax2.plot_wireframe(X, Y, zi, rstride = 1, cstride = 1)
ax2.view_init(28, -144) 

plt.show()
于 2013-09-26T11:23:21.870 回答