Skip to main content
 首页 » 编程设计

python之如何使用笛卡尔坐标在 matplotlib 中绘制球体

2024年11月01日15bonelee

我想使用 matplotlib 绘制一个单位半径的球体。大多数示例和文档都是通过使用极坐标来完成的,我的方法是使用笛卡尔坐标。当我仅使用 np.sqrt 编写代码时只显示了上半部分,所以我定义了一个函数 sq 只接收错误消息 ValueError: The truth value of an array with more than one element is ambiguous.使用 a.any() 或 a.all()

import numpy as np 
import matplotlib.pyplot as plt 
def sq(x): 
    if x>=0: 
        return np.sqrt(x) 
    else: 
        return -np.sqrt(abs(x)) 
ax = plt.axes(projection="3d") 
xlist=np.linspace(-1.0,1.0,50) 
ylist=np.linspace(-1.0,1.0,50) 
r=np.linspace(1.0,1.0,50) 
X,Y= np.meshgrid(xlist,ylist) 
Z=sq(r**2-X**2-Y**2) 
cp=ax.plot_wireframe(X,Y,Z,color="r") 
plt.title('The unit sphere') 
plt.show() 

我怎样才能编辑显示下半部分的程序?

请您参考如下方法:

如果您需要正在创建的半球的另一半,只需绘制相同的半球但为负。您的方法行不通,因为对于给定的 x,y 坐标,您需要 2 个值(即 +/- z)。因此,即使您将给定负 X 的 Z 值设置为负,您仍然无法获得球体。如果您想要更平滑的绘图,那么您需要使用极坐标计算来获得正确的球体边界值。

import numpy as np 
import matplotlib.pyplot as plt 
from mpl_toolkits import mplot3d 
 
ax = plt.axes(projection="3d") 
xlist=np.linspace(-1.0,1.0,50) 
ylist=np.linspace(-1.0,1.0,50) 
r=np.linspace(1.0,1.0,50) 
X,Y= np.meshgrid(xlist,ylist) 
 
Z=np.sqrt(r**2-X**2-Y**2) #Use np.sqrt like you had before 
 
cp=ax.plot_wireframe(X,Y,Z,color="r") 
cp=ax.plot_wireframe(X,Y,-Z,color="r") # Now plot the bottom half 
 
 
plt.title('2D Contour Plot of The unit sphere') 
plt.show() 

注意

如果您希望球体看起来更像使用这种方法的球体,您可以像这样增加分辨率并增加 rstride 和 cstride。您也可以旋转轴。例如:

xlist=np.linspace(-1.0,1.0,10000) 
ylist=np.linspace(-1.0,1.0,10000) 
X,Y= np.meshgrid(xlist,ylist) 
Z=np.sqrt(1**2-X**2-Y**2) #Note your r is redundant, use 1. 
 
ax = plt.axes(projection="3d") 
 
cp=ax.plot_wireframe(X,Y,Z,color="r", rstride=1000, cstride=1000) 
cp=ax.plot_wireframe(X,Y,-Z,color="r", rstride=1000, cstride=1000) 
 
 
plt.title('2D Contour Plot of The unit sphere') 
plt.show()