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

2024-04-20 10:31:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我想画一个单位半径的球体matplotlib.Most大多数其中的例子和文献都是用极坐标来做的,按我的方法就是用笛卡尔。什么时候我只使用np.sqrt公司只显示了上面的部分,所以我定义了一个函数sq,只接收错误消息ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or 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()

我怎样才能编辑程序,这将显示较低的部分也?你知道吗


Tags: theimportreturnmatplotlibasnpsq半径
1条回答
网友
1楼 · 发布于 2024-04-20 10:31:02

如果你需要你正在创建的半球的另一半,只需简单地绘制同一个半球,但负片。您的方法不起作用,因为对于给定的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()

enter image description here

注意

如果您希望使用这种方法使球体看起来更像球体,可以增加分辨率并增加rstridecstride,如下所示。你也可以旋转你的轴。例如:

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()

enter image description here

相关问题 更多 >