使用Matplotlib绘制椭圆体

时间:2011-10-19 09:54:55

标签: python matplotlib

有没有人有绘制椭球的示例代码? matplotlib网站上有一个球体,但椭圆体没有。我正在尝试绘制

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

其中c是一个定义椭球的常量(如10)。我尝试了meshgrid(x,y)路线,重新设计了等式,因此z位于一边,但sqrt是个问题。 matplotlib球体示例适用于角度u,v,但我不知道如何使用椭圆体。

3 个答案:

答案 0 :(得分:18)

以下是通过球坐标来完成的方法:

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

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

此解决方案受到exampleMatplotlib's gallery的强烈启发。

答案 1 :(得分:9)

以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为中心并且想要绘制它。

答案 2 :(得分:1)

如果你有一个由任意协方差矩阵 cov 和偏移量 bias 指定的椭球,你不需要需要找出椭球的直观参数来得到形状。具体来说,您不需要单独的轴或旋转。矩阵的全部意义在于它将单位球体(由单位矩阵表示)转换为椭圆。

开头

u = np.linspace(0, 2 * np.pi, 100)
v = np.linspace(0, np.pi, 100)

制作单位球体

x = np.outer(np.cos(u), np.sin(v))
y = np.outer(np.sin(u), np.sin(v))
z = np.outer(np.ones_like(u), np.cos(v))

现在变换球体:

ellipsoid = (cov @ np.stack((x, y, z), 0).reshape(3, -1) + bias).reshape(3, *x.shape)

您可以像以前一样绘制结果:

ax.plot_surface(*ellipsoid, rstride=4, cstride=4, color='b', alpha=0.75)