Python:在Matplotlib中绘制均匀间隔的球体

时间:2017-08-16 21:15:46

标签: python matplotlib plot 3d mayavi

我试图创建一个有点像这样的情节:

enter image description here

在所有极小值都有球的地方。

表面可以用sin(x)* sin(y)图近似:

import numpy as np
import matplotlib.pyplot as plt

def func(x, y):
  return np.sin(2*np.pi*x)*np.sin(2*np.pi*y) / 3

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-1.0, 1.0, 0.05)
X, Y = np.meshgrid(x, y)
zs = np.array([func(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

ax.plot_surface(X, Y, Z, color="grey")
ax.set_zlim3d(-1,1)

plt.show()

但是,我不确定如何在其中添加均匀间隔的球体。有人能帮忙吗?

2 个答案:

答案 0 :(得分:2)

您需要确定函数的最小值,它是(在您的参数化时)(x =整数+ 0.25,y =整数+ 0.75)或反之。然后,您可以使用球面坐标简单地对球体进行参数化(例如,如此处所示:python matplotlib: drawing 3D sphere with circumferences)并绘制球体。

现在有一些好消息和一些坏消息:

1。)好消息是正确确定了最小值并且创建了球体。在下面的图中,您可以看到它们位于曲面图的蓝色部分正上方(蓝色部分确实显示最小值)。

2。)坏消息是你很难找到另一个球体实际正确渲染的角度。我不知道这种相当烦人的行为的解决方案,因此你可能不得不四处玩,直到你找到了正确的角度。玩得开心!

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def func(x, y):
  return np.sin(2*np.pi*x)*np.sin(2*np.pi*y) / 3

fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
x = y = np.arange(-2.0, 2.0, 0.05)

# Get the minima of the function.
minsx1 = np.arange(int(np.amin(x)) + 0.25, int(np.amax(x)) + 0.25 + 1, 1)
minsy1 = np.arange(int(np.amin(y)) + 0.75, int(np.amax(y)) + 0.75 + 1, 1)
minsx2 = np.arange(int(np.amin(x)) + 0.75, int(np.amax(x)) + 0.75 + 1, 1)
minsy2 = np.arange(int(np.amin(y)) + 0.25, int(np.amax(y)) + 0.25 + 1, 1)

X, Y = np.meshgrid(x, y)
zs = np.array([func(x,y) for x,y in zip(np.ravel(X), np.ravel(Y))])
Z = zs.reshape(X.shape)

# Color map for better detection of minima (blue)
ax.plot_surface(X, Y, Z, cmap="viridis")
ax.set_zlim3d(-1,1)

# Spherical coordinates
r = 0.15
phi = np.linspace(0, 2 * np.pi, 30)
theta = np.linspace(0, np.pi, 30)

# Write spherical coordinates in cartesian coordinates.
x = r * np.outer(np.cos(phi), np.sin(theta))
y = r * np.outer(np.sin(phi), np.sin(theta))
z = r * np.outer(np.ones(np.size(phi)), np.cos(theta))

# Plot the spheres.
for xp in minsx1:
    for yp in minsy1:
        sphere = ax.plot_surface(x+xp, y+yp, z+0.35, color='r')
for xp in minsx2:
    for yp in minsy2:
        sphere = ax.plot_surface(x+xp, y+yp, z+0.35, color='r')
ax.view_init(elev=90, azim=0)
plt.savefig('test.png')
plt.show()

enter image description here

答案 1 :(得分:2)

使用matplotlib将不可避免地遇到隐藏在其他人后面的对象的问题。这也在matplotlib 3d FAQ中说明,建议使用mayavi

在mayavi,解决方案看起来像这样:

from mayavi import mlab
import numpy as np

### SURFACE '''
x,y = np.meshgrid(np.linspace(-2.5,2), np.linspace(-2,2))
f = lambda x,y: .4*np.sin(2*np.pi*x)*np.sin(2*np.pi*y)
z=f(x,y)
mlab.surf(x.T,y.T,z.T, colormap="copper")

### SPHERES '''
px,py = np.meshgrid(np.arange(-2,2)+.25, np.arange(-2,2)+.75)
px,py = px.flatten(),py.flatten()
pz = np.ones_like(px)*0.05
r = np.ones_like(px)*.4
mlab.points3d(px,py,pz,r, color=(0.9,0.05,.3), scale_factor=1)


mlab.show()

enter image description here