首页 > 解决方案 > 在曲面图中截断半个圆环

问题描述

我正在尝试使用matplotlib.

到目前为止,这是我的方法:

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

n = 100

# theta: poloidal angle; phi: toroidal angle
theta = np.linspace(0, 2.*np.pi, n)
phi   = np.linspace(0, 2.*np.pi, n)
theta, phi = np.meshgrid(theta, phi)

# R0: major radius; a: minor radius
R0, a = 2., 1.

# torus parametrization
x = (R0 + a*np.cos(theta)) * np.cos(phi)
y = (R0 + a*np.cos(theta)) * np.sin(phi)
z = a * np.sin(theta)

# "cut-off" half of the torus
x[x>0] = np.nan

fig = plt.figure()
ax1 = fig.add_subplot(111, projection='3d')
ax1.set_zlim(-3,3)
ax1.plot_surface(x, y, z, rstride=5, cstride=5,)

# elev: elevation angle in z-plane
# azim: azimuth angle in x,y plane
ax1.view_init(elev=15, azim=0)

plt.show()

这样做确实给了我半个圆环,但是其中一个切割面不清楚,如图所示(这里有问题的是左侧切割面)。在此处输入图像描述

任何想法如何制作干净的切割表面?

标签: pythonnumpymatplotlib3d

解决方案


用 s 切割表面nan通常会这样做。这是因为表面的补丁是在输入数据的子集上使用线性插值绘制的,并且nan边界上有 s 将导致nan某些边缘补丁的值的结果。

在您的特定情况下,您可以将环形角限制为半个圆环:

theta = np.linspace(0, 2*np.pi, n) 
phi   = np.linspace(0, np.pi, n) 

您还必须为漂亮的纵横比设置手动 x/y 限制:

ax1.axis([-3, 3]*2)

结果

facecolors通过传递to的显式数组plot_surface并操纵内部值的透明度,有一个非常通用但实用的替代方案。除非您努力工作,否则这将比默认设置更难看,因为单色会缺少阴影。这是我的意思的一个非常基本(和丑陋)的例子:

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

n = 100 

# theta: poloidal angle; phi: toroidal angle 
theta = np.linspace(0, 2*np.pi, n) 
phi   = np.linspace(0, 2*np.pi, n) 
theta, phi = np.meshgrid(theta, phi) 

# R0: major radius; a: minor radius 
R0, a = 2., 1. 

# torus parametrization 
x = (R0 + a*np.cos(theta)) * np.cos(phi) 
y = (R0 + a*np.cos(theta)) * np.sin(phi) 
z = a * np.sin(theta) 

# "cut-off" half of the torus using transparent colors 
c = np.full(x.shape + (4,), [0, 0, 0.85, 1])  # shape (nx, ny, 4)
c[x>0, -1] = 0 # set these to transparent 

fig = plt.figure() 
ax1 = fig.add_subplot(111, projection='3d') 
ax1.set_zlim(-3,3) 
ax1.plot_surface(x, y, z, facecolors=c, rstride=5, cstride=5,)

# elev: elevation angle in z-plane 
# azim: azimuth angle in x,y plane 
ax1.view_init(elev=15, azim=0) 

plt.show() 

facecolors 示例结果


推荐阅读