Skip to main content
 首页 » 编程设计

python之表面在 Matplotlib 3D 图中消失

2024年10月17日8xing901022

我正在尝试绘制一个切出线段的球体。我想我已经正确地创建了坐标,但我发现当我在切片球体周围平移时,内表面消失了。我究竟做错了什么?如果相关的话,这是在 openSUSE Leap 42.1 上使用后端 TkAgg 的 Python 2.7.3 和 Matplotlib 1.5.1。

代码:

from mpl_toolkits.mplot3d import Axes3D 
from matplotlib import pyplot as pl 
import numpy as np 
 
fig = pl.figure() 
ax = fig.add_subplot(111, projection='3d') 
 
phi = np.linspace(0.5*np.pi, 2.0*np.pi, 100) 
theta = np.linspace(0, np.pi, 100) 
 
x = np.outer(np.cos(phi), np.sin(theta)) 
y = np.outer(np.sin(phi), np.sin(theta)) 
z = np.outer(np.ones(np.size(phi)), np.cos(theta)) 
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b') 
 
r = np.linspace(0.,1.,25) 
x = np.outer(r, np.sin(theta)) 
y = 0.*x 
z = np.outer(r, np.cos(theta)) 
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='g') 
 
ax.view_init(30.,60.) 
pl.show() 

请您参考如下方法:

事实证明,这是一个很常见的问题,在 FAQ 中提到过。 :

My 3D plot doesn’t look right at certain viewing angles

This is probably the most commonly reported issue with mplot3d. The problem is that – from some viewing angles – a 3D object would appear in front of another object, even though it is physically behind it. This can result in plots that do not look “physically correct.”

Unfortunately, while some work is being done to reduce the occurance of this artifact, it is currently an intractable problem, and can not be fully solved until matplotlib supports 3D graphics rendering at its core.

在这种情况下,您可以通过分别绘制球体的四分之三来创建粗略的修复。例如

from mpl_toolkits.mplot3d import Axes3D 
from matplotlib import pyplot as pl 
import numpy as np 
 
fig = pl.figure() 
ax = fig.add_subplot(111, projection='3d') 
 
theta = np.linspace(0, np.pi, 100) 
 
# first quarter 
phi = np.linspace(0.5*np.pi, 1.0*np.pi, 34) 
x = np.outer(np.cos(phi), np.sin(theta)) 
y = np.outer(np.sin(phi), np.sin(theta)) 
z = np.outer(np.ones(np.size(phi)), np.cos(theta)) 
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b') 
 
# second quarter 
phi = np.linspace(1.0*np.pi, 1.5*np.pi, 34) 
x = np.outer(np.cos(phi), np.sin(theta)) 
y = np.outer(np.sin(phi), np.sin(theta)) 
z = np.outer(np.ones(np.size(phi)), np.cos(theta)) 
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b') 
 
# third quarter 
phi = np.linspace(1.5*np.pi, 2.0*np.pi, 34) 
x = np.outer(np.cos(phi), np.sin(theta)) 
y = np.outer(np.sin(phi), np.sin(theta)) 
z = np.outer(np.ones(np.size(phi)), np.cos(theta)) 
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='b') 
 
r = np.linspace(0.,1.,25) 
x = np.outer(r, np.sin(theta)) 
y = 0.*x 
z = np.outer(r, np.cos(theta)) 
ax.plot_surface(x, y, z, rstride=4, cstride=4, color='g') 
 
ax.view_init(30.,60.) 
pl.show()