用Matplotlib绘制椭球 [英] Plotting Ellipsoid with Matplotlib
问题描述
有人有绘制椭圆体的示例代码吗? matplotlib
站点上的球体只有一个,而椭球体则没有.我正在尝试
Does anyone have sample code for plotting ellipsoids? There is one for sphere on matplotlib
site, but nothing for ellipsoids. I am trying to plot
x**2 + 2*y**2 + 2*z**2 = c
其中,c
是定义椭圆形的常数(如10).我尝试了meshgrid(x,y)
路线,对方程进行了重新设计,使z
在一侧,但是sqrt
是一个问题. matplotlib
球面示例可与角度u,v
一起使用,但是我不确定如何对椭球进行处理.
where c
is a constant (like 10) that defines an ellipsoid. I tried the meshgrid(x,y)
route, reworked the equation so z
is on one side, but the sqrt
is a problem. The matplotlib
sphere example works with angles, u,v
, but I am not sure how to work that for ellipsoid.
推荐答案
以下是如何通过球坐标进行的操作:
Here is how you can do it via spherical coordinates:
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()
生成的图类似于
上面的程序实际上产生了看起来更漂亮的正方形"图形.
The program above actually produces a nicer looking "square" graphics.
此解决方案的灵感来自
This solution is strongly inspired from the example in Matplotlib's gallery.
这篇关于用Matplotlib绘制椭球的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!