用Matplotlib绘制椭球体

2024-06-12 00:48:28 发布

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

有没有绘制椭球体的示例代码?对于matplotlib站点上的球体有一个,但对于椭球体则没有。我在策划

x**2 + 2*y**2 + 2*z**2 = c

其中c是定义椭球体的常数(如10)。我尝试了meshgrid(x,y)路径,重新计算了方程,使z位于一边,但sqrt是个问题。matplotlib球体示例可以处理角度,u,v,但我不确定如何处理椭球体。


Tags: 代码路径示例定义站点matplotlib常数绘制
2条回答

基于EOL的答案。有时,您有一个矩阵格式的椭球体:

A和c,其中A是椭球矩阵,c是表示椭球中心的向量。

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

# your ellispsoid and center in matrix form
A = np.array([[1,0,0],[0,2,0],[0,0,2]])
center = [0,0,0]

# find the rotation matrix and radii of the axes
U, s, rotation = linalg.svd(A)
radii = 1.0/np.sqrt(s)

# now carry on with EOL's answer
u = np.linspace(0.0, 2.0 * np.pi, 100)
v = np.linspace(0.0, np.pi, 100)
x = radii[0] * np.outer(np.cos(u), np.sin(v))
y = radii[1] * np.outer(np.sin(u), np.sin(v))
z = radii[2] * np.outer(np.ones_like(u), np.cos(v))
for i in range(len(x)):
    for j in range(len(x)):
        [x[i,j],y[i,j],z[i,j]] = np.dot([x[i,j],y[i,j],z[i,j]], rotation) + center

# plot
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.plot_wireframe(x, y, z,  rstride=4, cstride=4, color='b', alpha=0.2)
plt.show()
plt.close(fig)
del fig

所以,这里没有太多的新内容,但是如果你有一个椭球体,它是矩阵形式的,是旋转的,也许不是以0,0,0为中心的,并且想要绘制它的话。

下面是如何通过球面坐标来实现的:

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

fig = plt.figure(figsize=plt.figaspect(1))  # Square figure
ax = fig.add_subplot(111, projection='3d')

coefs = (1, 2, 2)  # Coefficients in a0/c x**2 + a1/c y**2 + a2/c z**2 = 1 
# Radii corresponding to the coefficients:
rx, ry, rz = 1/np.sqrt(coefs)

# Set of all spherical angles:
u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)

# Cartesian coordinates that correspond to the spherical angles:
# (this is the equation of an ellipsoid):
x = rx * np.outer(np.cos(u), np.sin(v))
y = ry * np.outer(np.sin(u), np.sin(v))
z = rz * np.outer(np.ones_like(u), np.cos(v))

# Plot:
ax.plot_surface(x, y, z,  rstride=4, cstride=4, color='b')

# Adjustment of the axes, so that they all have the same span:
max_radius = max(rx, ry, rz)
for axis in 'xyz':
    getattr(ax, 'set_{}lim'.format(axis))((-max_radius, max_radius))

plt.show()

结果图类似于

enter image description here

上面的程序实际上产生了一个好看的“正方形”图形。

这个解决方案的灵感来自于Matplotlib's gallery中的example

相关问题 更多 >